I read the posting and something I can’t understand is the difference between setValue(curr + 1)
and setValue(prev => prev + 1)
Is there anybody who can give me an example in reality so that I can test it on my side?
He called setValue inside the event handler, but what if I call it in another?
Is it a good practice for me to use latter one whenever I use useState
?
https://levelup.gitconnected.com/4-usestate-mistakes-you-should-avoid-in-react-0d9d676869e2
2
Answers
The
setValue(value + 1)
is usually used when the current state is not dependent on the previous start, like updating the name.And this
setValue((value) => value+1)
is used when the current state is dependent on the previous start.Below is an example,
I hope this helps
The difference between
setValue(curr + 1)
andsetValue(prev => prev + 1)
in a React component usinguseState
lies in how they update the state.setValue(curr + 1)
This approach directly uses the current value of
curr
to set the new state. For example:Here,
curr
is the current state value when thehandleClick
function is called. This approach works fine in simple scenarios but can lead to issues if the state updates happen asynchronously or if there are multiple updates in a short period.setValue(prev => prev + 1)
This approach uses a function that receives the previous state value (
prev
) and returns the new state. For example:This method is generally safer and more predictable because it ensures that the state update is based on the most recent state value, even if multiple updates are queued.
Example to Test
Here’s a simple example you can run to see the difference:
Explanation
Direct Update (
handleDirectUpdate
):value
tocurr + 1
immediately.value
tocurr + 1
again. However,curr
might be stale (not the latest state value), so the second update may not work as expected.Functional Update (
handleFunctionalUpdate
):value
toprev + 1
immediately.value
toprev + 1
again using the most recent state value. This approach ensures that the state is correctly incremented regardless of the timing.Good Practice
It is generally a good practice to use the functional form (
setValue(prev => prev + 1)
) whenever you need to update state based on the previous state value. This approach is more robust and handles asynchronous state updates more reliably.