State with useState
The big one. State is data that changes over time — and when it changes, React re-renders the UI automatically.
What you will learn
- Add state with the useState hook
- Update state to re-render the UI
- Understand why you never change state directly
State = data that changes
A hook is a special function that adds powers to a component. useState gives a component a piece of memory (state). When you update it, React re-renders to match.
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount(count - 1)}>-1</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}Note: Output:
Count: 0 with three buttons (+1, -1, Reset). Click +1 and it reads Count: 1, then Count: 2, and so on. You never touched the page yourself — you changed state with setCount and React redrew the number.
How useState works
Walk through the counter: useState(0) sets up a piece of memory starting at 0 and hands back two things in an array — the current value (count) and a function to change it (setCount). The heading shows {count}. Each button calls setCount with a new value; setCount(count + 1) adds one, setCount(count - 1) subtracts one, setCount(0) resets. Every call to setCount tells React to re-run the component and repaint with the new number.
const [count, setCount] = useState(0)creates statecountstarting at0.countis the current value (read it in your JSX).setCountis the only way to change it — and it triggers a re-render.
Watch out: Never change state directly (count++ or count = 5). Always use the setter (setCount(...)). Direct changes will not update the UI.
State can hold text too. This next example stores what you type and shows it back live as you go:
function App() {
const [name, setName] = useState("");
return (
<div>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Type your name"
/>
<h3>Hello, {name || "stranger"}!</h3>
</div>
);
}State is not just for numbers. Here name holds text, starting empty (""). The input shows value={name}, and every keystroke fires onChange, which calls setName(e.target.value) — e.target.value is whatever is currently typed in the box. That updates state, React re-renders, and the heading below updates instantly. The name || "stranger" shows “stranger” while the box is empty.
Note: Output: An input box and a heading. Empty box → Hello, stranger!. Type “Asha” → the heading updates live to Hello, Asha! as you type.
Tip: Mental model: UI = f(state). You do not touch the DOM; you change state, and React redraws the UI to match. This is the core idea of React.
Q. How do you update a state variable created with useState?
✍️ Practice
- Build a counter with +1, -1 and reset buttons.
- Build a live text input that greets the user as they type.
🏠 Homework
- Build a “like” button that counts likes, and a toggle that shows/hides a paragraph using a boolean state.