State and Events · Lesson 8 of 31
React useState Hook
Props come from the parent and can't be changed by the component. For data that changes inside a component – a counter, a typed search term, whether a menu is open – React gives you state, through the useState hook. It's the hook you'll use most, and understanding exactly how it updates avoids the most common React bugs.
In this lesson
- Declaring and updating state
- Why a normal variable doesn't work
- State as a snapshot, and updater functions
- Batching, lazy initial state and the rules of hooks
Declaring state
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0); // [current value, setter], initial value 0
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Add</button>
<button onClick={() => setCount(0)}>Reset</button>
<button onClick={() => setIsOpen(!isOpen)}>{isOpen ? "Close" : "Open"} menu</button>
{isOpen && <ul><li>Profile</li><li>Settings</li></ul>}
</div>
);
}
Count: 0 [Add] [Reset] [Open menu] › click “Add” Count: 1 [Add] [Reset] [Open menu] › click “Add” Count: 2 [Add] [Reset] [Open menu] › click “Open menu” Count: 2 [Add] [Reset] [Close menu] • Profile • Settings › click “Reset” Count: 0 [Add] [Reset] [Close menu] • Profile • Settings
useState returns a pair, which we destructure. Calling the setter stores the new value and asks React to render the component again; on that render, useState returns the new value.
Why a plain variable doesn't work
export default function App() {
let count = 0; // reset to 0 on every render
function handleClick() {
count = count + 1; // changes the variable…
console.log("count is now", count);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Add</button>
</div>
);
}
Count: 0 [Add] › click “Add” Count: 0 [Add] console: count is now 1 › click “Add” Count: 0 [Add] console: count is now 2
The variable changes, but nothing re-renders, so the screen stays at 0. And even if something else caused a render, let count = 0 would run again. State fixes both problems: React keeps the value between renders, and setting it triggers a render.
State is a snapshot
Inside one render, count is a constant. Calling the setter doesn't change it immediately – it schedules the next render:
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
function addThree() {
setCount(count + 1); // count is 0 → schedule 1
setCount(count + 1); // count is still 0 → schedule 1
setCount(count + 1); // still 0 → schedule 1
console.log("inside handler:", count);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={addThree}>+3</button>
</div>
);
}
Count: 0 [+3] › click “+3” Count: 1 [+3] console: inside handler: 0
The count goes to 1, not 3, and the log still prints 0. To update based on the previous state, pass an updater function:
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
function addThree() {
setCount((c) => c + 1); // React passes the latest pending value
setCount((c) => c + 1);
setCount((c) => c + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={addThree}>+3</button>
</div>
);
}
Count: 0 [+3] › click “+3” Count: 3 [+3] › click “+3” Count: 6 [+3]
How React processes the queue for one click
- c => c + 10 → 1
- c => c + 11 → 2
- c => c + 12 → 3
- rendercount = 3
When to use an updater
Use setX(prev => …) whenever the new value depends on the old one and the update might run more than once before a render – multiple calls in a handler, timers, or async callbacks. Setting a value that doesn't depend on the old one (setCount(0), setName(e.target.value)) doesn't need it.
Batching: one render for many updates
import { useState } from "react";
export default function App() {
const [first, setFirst] = useState("Asha");
const [last, setLast] = useState("Verma");
console.log("render:", first, last);
return (
<button onClick={() => { setFirst("Ravi"); setLast("Kumar"); }}>
Change name
</button>
);
}
render: Asha Verma › click “Change name” render: Ravi Kumar
React batches all state updates from the same event into a single re-render – two setters, one render. Since React 18 this also applies inside promises, timeouts and native event handlers.
Lazy initial state
import { useState } from "react";
function loadDraft() {
console.log("reading draft…"); // pretend this is expensive
return "Dear team,";
}
export default function App() {
const [text, setText] = useState(loadDraft); // pass the function, don't call it
return <textarea aria-label="Message" value={text} onChange={(e) => setText(e.target.value)} />;
}
[Dear team,] console: reading draft… › type “ hi” into Message [Dear team, hi]
useState(loadDraft) calls the function only on the first render. useState(loadDraft()) would call it on every render and throw the result away – wasteful if it reads localStorage or does heavy work.
The rules of hooks
- Call hooks only at the top level of a component or custom hook – never inside
if, loops or nested functions. React identifies eachuseStateby its call order. - Call hooks only from React function components or custom hooks, not from regular functions.
- Each component instance has its own state: render
<Counter />twice and you get two independent counters.
The eslint-plugin-react-hooks rules (included in the Vite template) catch violations as you type.
Practice
Try it yourself
Build a quantity picker: − and + buttons, never below 1 or above 10, and a total for ₹499 each.
Show solution
import { useState } from "react"; export default function App() { const [qty, setQty] = useState(1); return ( <div> <button onClick={() => setQty((q) => Math.max(1, q - 1))} disabled={qty === 1}>−</button> <span> {qty} </span> <button onClick={() => setQty((q) => Math.min(10, q + 1))} disabled={qty === 10}>+</button> <p>Total: ₹{qty * 499}</p> </div> ); }[− (disabled)] 1 [+] Total: ₹499 › click “+” [−] 2 [+] Total: ₹998 › click “+” [−] 3 [+] Total: ₹1497 › click “−” [−] 2 [+] Total: ₹998
Quick check
Why does setCount(count + 1) three times only add 1?
count is a snapshot for this render; all three calls compute 0 + 1. Use the updater form.
How many renders do two setters in one click cause?
One – React batches them.
Can you call useState inside an if?
No – hooks must be called at the top level, in the same order every render.
Summary
- useState keeps a value between renders; the setter stores a new value and re-renders.
- State is a snapshot: use setX(prev => …) when the next value depends on the previous one.
- Updates are batched; pass a function for expensive initial values; follow the rules of hooks.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.