Hello folks! welcome back to a new section of our tutorial on ReactJS. In this section of our tutorial on ReactJS, we will be studying about the ReactJS state management using React Hooks.
React introduces an entirely new concepts known as React Hooks from React version 16.8. Though, it is a relatively new concept, it allows the React functional component to have its own state and life-cycle. Also, React Hooks allows functional component to use many of the features not available earlier.
Let us see how to do state management in a functional component using React Hooks in this tutorial.
React introduces an entirely new concepts known as React Hooks from React version 16.8. Though, it is a relatively new concept, it allows the React functional component to have its own state and life-cycle. Also, React Hooks allows functional component to use many of the features not available earlier.
Let us see how to do state management in a functional component using React Hooks in this tutorial.
What is React Hooks
React Hooks are special functions provided by React to handle a particular functionality inside a React functional component. React provides a Hook function for all supported feature. For instance, React gives useState() function to manage the state in a functional component. When a functional component uses React Hooks, React Hooks attaches itself into the component and then provides additional functionality.
The general syntax of useState() Hook is as follows -
The general syntax of useState() Hook is as follows -
const [<state variable>, <state update function>] = useState(<initial value>);
For example, state management in a clock component using Hooks can be performed as specified below -
const [currentDateTime, setCurrentDateTime] = useState(new Date()); setInterval(() => setCurrentDateTime(new Date()), 1000);
Here,
- currentDateTime is a variable used to hold current date and time (returned by setState())
- setCurrentDate() is a function that is used to set the current date and time (returned by setState()).
Create a Stateful Component
Let us recreate our clock component using Hooks in the tutorial.
Firstly, create a new react application react-clock-hook-app using the Create React App or Rollup bundler by following guidelines in Creating a React application tutorial.
Next, open the application in your favorite editor.
Next, create an src folder beneath the root directory of the application.
Next, create component folder under the src folder.
Create a file, Clock.js under src/component folder and start editing.
Next, import React library and React state Hook, setState.
Firstly, create a new react application react-clock-hook-app using the Create React App or Rollup bundler by following guidelines in Creating a React application tutorial.
Next, open the application in your favorite editor.
Next, create an src folder beneath the root directory of the application.
Next, create component folder under the src folder.
Create a file, Clock.js under src/component folder and start editing.
Next, import React library and React state Hook, setState.
import React, { useState } from 'react';
Next, create Clock component.
function Clock() { }
Next, create state Hooks to maintain date and time.
const [currentDateTime, setCurrentDateTime] = useState(new Date());
Next, set date and time for every second.
setInterval(() => setCurrentDateTime(new Date()), 1000);
Next, create the user interface to show the current date and time via currentDateTime and return it.
return ( <div><p>The current time is {currentDateTime.toString()}</p></div> );
Finally, export the component via the code snippet.
export default Clock;
The complete code of the Clock component is as follows -
import React, { useState } from 'react'; function Clock(props) { const [currentDateTime, setCurrentDateTime] = useState(new Date()); setInterval(() => setCurrentDateTime(new Date()), 1000); return ( <div><p>The current time is {currentDateTime.toString()}</p></div> ); } export default Clock;
Next, create a file, index.js beneath the src folder and use Clock component.
import React from 'react'; import ReactDOM from 'react-dom'; import Clock from './components/Clock'; ReactDOM.render( <React.StrictMode> <Clock /> </React.StrictMode>, document.getElementById('root') );
Finally, create a public folder under the root folder and create index.html file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Clock</title> </head> <body> <div id="root"></div> <script type="text/JavaScript" src="./index.js"></script> </body> </html>
Next, serve the application making use of npm command.
npm start
Next, open the web browser and then enter http://localhost:3000 in the address bar and press enter. The application will display the time and update it every second.
The current time is Wed Jan 19 2022 07:10:18 GMT+0530 (West African Time)
The above application works well. But, the setCurrentDateTime set to execute in every second has to be removed when the React application ends. We can do this by making use of another Hook, useEffect provided by React. We will be studying about useEffect in our next tutorial.
Introducing State in Expense Manager App
Let us introduce state management in the expense manager application by adding a simple feature to remove an expense item using Hooks in this tutorial.
Open expense-manager application in your favorite editor.
Create a new file, ExpenseEntryItemListFn.js under src/component folder and then start editing.
Next, import React library and React state Hooks, setState.
Open expense-manager application in your favorite editor.
Create a new file, ExpenseEntryItemListFn.js under src/component folder and then start editing.
Next, import React library and React state Hooks, setState.
import React, { useState } from 'react';
Next, import the css, ExpenseEntryItem.css.
import './ExpenseEntryItemList.css'
Next, generate the ExpenseEntryItemListFn component.
function ExpenseEntryItemListFn(props) { }
Next, initialize the React state Hooks of the component with the expense items passed into the components through properties.
const [items, setItems] = useState(props.items);
Next, create event handlers to highlight the rows.
function handleMouseEnter(e) { e.target.parentNode.classList.add("highlight"); } function handleMouseLeave(e) { e.target.parentNode.classList.remove("highlight"); } function handleMouseOver(e) { console.log("The mouse is at (" + e.clientX + ", " + e.clientY + ")"); }
Next, create an event handler to remove the selected items using items and setItems().
function handleDelete(id, e) { e.preventDefault(); console.log(id); let newItems = []; items.forEach((item, idx) => { if (item.id != id) newItems.push(item) }) setItems(newItems); }
Next, create getTotal() method to calculate the total amount.
function getTotal() { let total = 0; for (var i = 0; i < items.length; i++) { total += items[i].amount } return total; }
Next, create a user interface to display the expenses by looping over the items.
const lists = items.map((item) => <tr key={item.id} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> <td><a href="#" onClick={(e) => handleDelete(item.id, e)}>Remove</a></td> </tr> );
Next, create the complete UI to display the expenses and return it.
return ( <table onMouseOver={handleMouseOver}> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> <th>Remove</th> </tr> </thead> <tbody> {lists} <tr> <td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td> <td colSpan="4" style={{ textAlign: "left" }}> {getTotal()} </td> </tr> </tbody> </table> );
READ: ReactJS | Use Component
Finally, export the function as shown below -
export default ExpenseEntryItemListFn;
The full code of the ExpenseEntryItemListFn is as follows -
import React, { useState } from 'react'; import './ExpenseEntryItemList.css' function ExpenseEntryItemListFn(props) { const [items, setItems] = useState(props.items); function handleMouseEnter(e) { e.target.parentNode.classList.add("highlight"); } function handleMouseLeave(e) { e.target.parentNode.classList.remove("highlight"); } function handleMouseOver(e) { console.log("The mouse is at (" + e.clientX + ", " + e.clientY + ")"); } function handleDelete(id, e) { e.preventDefault(); console.log(id); let newItems = []; items.forEach((item, idx) => { if (item.id != id) newItems.push(item) }) setItems(newItems); } function getTotal() { let total = 0; for (var i = 0; i < items.length; i++) { total += items[i].amount } return total; } const lists = items.map((item) => <tr key={item.id} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> <td><a href="#" onClick={(e) => handleDelete(item.id, e)}>Remove</a></td> </tr> ); return ( <table onMouseOver={handleMouseOver}> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> <th>Remove</th> </tr> </thead> <tbody> {lists} <tr> <td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td> <td colSpan="4" style={{ textAlign: "left" }}> {getTotal()} </td> </tr> </tbody> </table> ); } export default ExpenseEntryItemListFn;
Next, update the index.js and then add the ExpenseEntryItemListFn component.
import React from 'react'; import ReactDOM from 'react-dom'; import ExpenseEntryItemListFn from './components/ExpenseEntryItemListFn' const items = [ { id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" }, { id: 2, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" }, { id: 3, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" }, { id: 4, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category: "Academic" }, { id: 5, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" }, { id: 6, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" }, { id: 7, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" }, { id: 8, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" }, { id: 9, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" }, { id: 10, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" } ] ReactDOM.render( <React.StrictMode> <ExpenseEntryItemListFn items={items} /> </React.StrictMode>, document.getElementById('root') );
Next, serve the application making use of npm command.
npm start
Next, open the web browser and then enter http://localhost:3000 in the address bar and press enter.
Finally, to remove an expense item, click on the corresponding remove link. It's going to remove the corresponding item and refresh the user interface as shown below -
Finally, to remove an expense item, click on the corresponding remove link. It's going to remove the corresponding item and refresh the user interface as shown below -
Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we will be studying about ReactJS Component Life Cycle.
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.