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.
How can you update the state in React?
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: