I recently saw a React project, in which incrementing a state variable was done like this:
const [count, setCount] = useState(0)
.....
setCount(count + 1 )
This directly sets the state to count + 1. However, this is not the right approach because if count is updated multiple times in quick succession, React may batch the updates for performance reasons, and all the updates might use the same initial value of count, leading to incorrect results.
Instead of doing this, functional updates should be used.
Functional state update is the approach of updating a state variable based on its previous value using a function provided to the state setter.
setCount((count) => count + 1);
This uses a function to update the state. The function receives the previous state as its argument and returns the new state. This ensures that each update is applied correctly even if multiple updates are batched together because each update uses the most recent state when it's applied.
I know pretty basic, but still wanted to put it out there for anyone new to React. 👍
Top comments (0)