Lesson 1. Store a local state with useState 4. State updates are not synchronous
Just before we conclude this last lesson, let’s talk about a common mistake about updating states, although it existed before hooks (with class-components).
Here is a piece of code that doesn’t accomplish what you may expect:
Result
What we want to do is, when the button is clicked, adding to string a -,
then a +. But you’ll notice that only the + is added.
This is because when you call setString, it doesn’t update the state
immediately. More precisely, it doesn’t change string at all (notice it is a
constant).
This means that if you use string after calling setString, you will always
get the previous value, not the updated one.
Two solutions to fix our problem:
- Updating the state in one call to
setStringonly, or - Giving a callback to
setStringto update the state based on the current value (which will be updated after each call tosetString)
Here the fixed piece of code with both implementations:
Result