State with useState
State is data that belongs to a component and can change over time.
When state changes, React renders the component again with the new value.
useState is the hook that gives you that data.
The pattern
count is the current value
setCount is the function that queues a new value
0 is the initial value, used only on the first render
Why not a plain let?
A let variable resets every render. React would not know it should update the screen.
useState stores the value outside the single function call, then feeds it back next time.
Any kind of value
Numbers, strings, booleans, objects, arrays. Start with the simplest type that works.
Several state variables
Prefer two useState calls over one mega object, until the values always change together.
Hooks have rules
Only call useState at the top of a component or a custom hook.
Do not put it inside if, loops, or nested functions.
React matches hooks by call order. If that order jumps, state gets mixed up.
Tip: Name the setter set plus the name: count / setCount. Do not invent mystery verbs.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.