Let say I declare a local state using React hook useState()
:
const [count, setCount] = useState(0);
Later I would like to update the state and trigger the re-rendering:
<button onClick={() => setCount(count+1)}
<button onClick={() => setCount((prev_count) => prev_count+1)}
What is the difference between these 2 types of update?
Here it does not make any difference but once your application grows bigger and you have count
used at many places, there is a possibility that multiple setState
calls would be happening and queuing up data to be rendered to the DOM, and hence the actual value of count might not be what you think.
This is exactly why it is recommended to use the previous state in the callback. prevState
is always a reliable solution without tracing every state update to know what the count
is.