Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to update state to re-render the component in ReactJS ?

How to update state to re-render the component in ReactJS ?

The useState() hook in react allows us to declare a state variable that persists during the re-render cycles. If we want to re-render the component then we can easily do so by calling the setState() function which is obtained by destructuring the array returned as a result of calling the useState() hook. Whenever we update the state using the setState() method it re-renders the current component and its child components.

Syntax:

const [state, setState] = useState(initialState)

When we call the setState function it receives the latest state snapshot. Then we can use it inside the setState() function and return the new value to which we want to update the new state value to. 

Syntax:

setState((latestState) => {
    // code logic
    return newState;
})

 Project setup

To create the new react project use the following command on command-line

npx create-react-app name_of_project

After running this command a new project will be created and your project structure will look as below.

App.js 

Javascript




import { useState } from 'react';
 
function App() {
    const [counter, setCounter] = useState(0);
 
    const handleIncrease = () => {
        setCounter((prev) => prev + 1);
    };
 
    const handleDecrease = () => {
        setCounter((prev) => prev - 1);
    };
 
    console.log('Rendering!!!');
 
    return (
        <div>
            <button onClick={handleDecrease}>
                decrease
            </button>
            <span> {counter} </span>
            <button onClick={handleIncrease}>
                increase
            </button>
        </div>
    );
}
 
export default App;


Step to run application: To start your application, use the following command on command-line.

npm start

Output: Open the browser and go to http://localhost:3000, you will see the following output.

Explanation: When we click the increase or decrease button, the handleIncrease or handleDecrease functions is called. Inside of these two functions we update the state using setState() function due to which our App component is rendered again and prints a message on the console.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments