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:

Similar Reads

1. Updating State Using Class Components:

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

2. Updating State Using Functional Components:

// Without prevStateconst [count, setCount] = useState(2);setCount(3);// With prevStateconst [count, setCount] = useState(2);setCount((prevCount) => prevCount + 1);...