State with useState
🏠The everyday picture
A scoreboard at a cricket match. When the score changes, the board is updated, and everyone watching sees the new score. State is the scoreboard; React redraws the screen whenever it changes.
📘What it really is
-
State is data a component remembers between redraws, which can change over time: what's typed in a search box, which tab is open, the list of enquiries.
-
useStatecreates a piece of state:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button type="button" onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
countis the current value;setCountis the only way to change it;-
0is the starting value. -
Calling the setter tells React to re-render (run the component function again) with the new value.
- Changing a normal variable does nothing on screen; only state changes cause re-renders.
useStateis a hook. Hooks are called at the top level of a component, never insideifstatements or loops (Module 34 explains why).
🖱️Try it
Add a "Show closed enquiries" button to the dashboard. Store showClosed in state (starting false), toggle it
on click with setShowClosed(!showClosed), and only show the closed panel when it's true. Change the button text
to match ("Show"/"Hide").
✅Quick check
You change a normal variable in a click handler, but the screen doesn't update. Why?
Show the answer
Only state changes (through the setter) cause React to re-render.
What does useState(0) return?
Show the answer
A pair: the current value, and a function to change it.
