Lesson 12 of 30
40%
Updating State Correctly
setState does not change the variable in the current line.
It asks React to render again with the new value.
That is why two setCount(count + 1) in one click can surprise you.
Updates are queued
javascript
Both lines read the same count. React batches them. You only go up by one.
Use the function form when the next value depends on the previous
javascript
React calls your function with the latest queued value.
Replace objects. Do not mutate them.
If you change a field on the same object, React may not see a change.
javascript
The spread copies the old fields, then you override score.
Replace arrays too
javascript
push, splice, and sort change the original array. Prefer methods that return a new one.
Updater with objects
javascript
Tip: If the UI ignores your setState, you probably mutated. Copy first, then set.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.