State & useState
Give your components a memory that persists across renders and triggers UI updates.
What it is
**State** is a component's memory. It allows a component to remember data between renders.
In functional components, you add state using the useState hook. It returns an array with exactly two values: the current state value, and a setter function to update it.
Why regular variables don't work
If you try to use a standard local variable (let count = 0) and update it (count++) on a button click, two things go wrong:
1. React doesn't know the variable changed, so it won't re-render the screen to show the new value.
2. Even if React did re-render, the function would run from the top again, resetting let count = 0 back to zero.
useState solves both problems: it persists the data across renders, and calling the setter function tells React to update the screen.
How to use it
You call const [count, setCount] = useState(0);. The 0 is the initial value.
When the user clicks a button, you call setCount(count + 1). This does not change the count variable immediately. Instead, it queues a re-render. React then calls your component function again, this time providing 1 as the new count.
The Memory Test
Compare a standard local variable against a React state variable. Notice how only the state variable manages to update the screen and remember its value.
Hint: The local variable actually changes in memory, but because it doesn't trigger a render, the UI is stuck. When the state button triggers a render, the function runs from the top, resetting localCount back to 0.
Click the Local button. Notice nothing happens. Click the State button. Notice the screen updates, and the Local variable resets to 0!
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- State allows a component to remember data between renders.
- Calling the setter function triggers a re-render.
- Never mutate state directly; always use the setter function.
- State variables are snapshots of the current render, not live reactive proxies.
Done with this concept?
Mark it complete to track your progress. No login needed.