Open In App

How can you update the state in React?

Last Updated : 24 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In React, you can update the state using the setState method provided by class components or the state updater function returned by the useState hook in functional components. The process is asynchronous, and React will re-render the component to reflect the updated state. Here’s how you can update the state in both class and functional components:

1. Updating State Using Class Components:

// Without prevState
this.setState({ count: 2 });

// With prevState
this.setState((prevState) => ({ count: prevState.count + 1 }));

2. Updating State Using Functional Components:

// Without prevState
const [count, setCount] = useState(2);
setCount(3);

// With prevState
const [count, setCount] = useState(2);
setCount((prevCount) => prevCount + 1);

Remember, state updates are asynchronous, and React provides mechanisms to handle side effects after the state is updated.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads