Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
  • Last Updated : 22 Oct, 2021
Improve Article
Save Article

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




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.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!