Sub topic 2
Declaring state with useState
This chapter assumes you can write function components and JSX, pass props, and use array destructuring and arrow functions. It covers what useState takes, what it returns, and the errors people commonly make when they first declare state.
What useState gives you
A function component runs from top to bottom on every render, so its local variables are created again each time. State is React's storage for values that must survive between renders. React keeps that storage outside your function and hands the current value back each time the component runs.
useState is a Hook, a function whose name starts with use and which connects a component to a React feature. You call it with an initial value:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}The call returns an array with exactly two items:
- The current state value. On the first render this is the initial value you passed,
0here. - A setter function. Calling it gives React a new value and asks React to render the component again.
You get the pair through array destructuring. The names are yours to choose, and the convention is [thing, setThing]. Nothing special happens in the names, because the position in the returned array is what matters.
The initial value is used once
The argument to useState only matters on the first render of that component instance. On later renders React ignores it and returns the stored value.
function Greeting({ name }) {
const [text, setText] = useState(name);
return (
<input value={text} onChange={e => setText(e.target.value)} />
);
}If the name prop changes from "Ada" to "Grace", the input keeps showing whatever text currently holds. The prop only seeded the state. A later chapter shows how to reset state when a prop changes. For now, treat a prop used as an initial value as a one-time copy.
What the setter does
Calling a setter does not change the variable in the code that is currently running. It schedules a new render, and during that render useState returns the new value.
function Demo() {
const [n, setN] = useState(0);
function handleClick() {
setN(n + 1);
console.log(n); // still the old value in this call
}
return <button onClick={handleClick}>{n}</button>;
}If n is 0, the log prints 0 even though the button will show 1 after the render. The destructured n is a const for that render, so the handler cannot see the new value. The chapter on snapshots covers this in detail.
Calling setN with the same value as the current one usually causes no visible work. React compares the new and old values with Object.is and can skip the update. It may still call your component function once more before it bails out, so do not rely on the function running or not running.
How the pieces connect
The diagram shows the sequence for one click.
Several state variables
A component can call useState as many times as it needs. Each call creates an independent piece of state.
import { useState } from 'react';
function SignupStep() {
const [email, setEmail] = useState('');
const [agreed, setAgreed] = useState(false);
const [attempts, setAttempts] = useState(0);
function submit() {
setAttempts(attempts + 1);
if (!agreed) return;
alert(`Signed up ${email}`);
}
return (
<>
<input value={email} onChange={e => setEmail(e.target.value)} />
<label>
<input
type="checkbox"
checked={agreed}
onChange={e => setAgreed(e.target.checked)}
/>
I agree
</label>
<button onClick={submit}>Sign up ({attempts})</button>
</>
);
}React does not identify these by name. It stores them in a list and matches each call to its slot by the order of calls. That is why the Rules of Hooks exist.
Rules that follow from call order
- Call Hooks only at the top level of a component or of another Hook. Do not call them inside conditions, loops, or nested functions.
- Call Hooks only from function components or custom Hooks, not from plain functions or class components.
function Broken({ show }) {
if (show) {
const [open, setOpen] = useState(false); // wrong: conditional Hook
}
const [name, setName] = useState(''); // slot index now depends on `show`
return null;
}When show flips between renders, the second call lands in a different slot, and React either throws an error or returns the wrong value. The linter rule react-hooks/rules-of-hooks catches this, so keep it enabled.
Each component instance has its own state
State belongs to a particular place in the tree, not to the function. Rendering <Counter /> twice gives two separate counts.
function Page() {
return (
<>
<Counter />
<Counter />
</>
);
}Clicking the first button does not affect the second. If two components need to show the same value, the state has to live in a shared parent, which a later chapter covers.
Storing functions and other special values
useState treats a function argument specially in two places.
| You pass | Where | What React does |
|---|---|---|
| A function to `useState(...)` | Initial value | Calls it once on the first render and uses the result (lazy initialization) |
| A function to `setX(...)` | Setter | Calls it with the pending state and uses the result (updater function) |
So you cannot store a function by passing it directly. To keep a callback in state, wrap it:
const [handler, setHandler] = useState(() => () => console.log('hi'));
setHandler(() => () => console.log('changed'));This is rare. If you find yourself doing it often, a useRef or a different design is usually a better fit.
Choosing what to put in state
Use state only for values that change over time and that affect what the component renders. Two common mistakes follow from ignoring that rule.
- A value that can be computed from props or other state should be a normal variable in the render, not state.
- A value that changes but does not affect the screen, such as a timer ID, belongs in a ref, not in state. A state update triggers a render, and here that render is wasted.
Start with the smallest set of state variables that describes what the user can change. Add more only when you need them.
Common errors when declaring state
- Forgetting to call the setter. Assigning
count = count + 1changes a localletor fails on aconst, and React never learns about it. No render happens. - Calling the setter during render. Writing
setCount(1)in the body of the component, outside a handler or an Effect, schedules a render that again calls the setter. This produces the error "Too many re-renders". - Passing a call instead of a function.
onClick={setCount(5)}runssetCount(5)while rendering. WriteonClick={() => setCount(5)}. - Expecting the new value right after the setter. The current render keeps its old value, as the
console.log(n)example showed. - Starting with
undefinedwhen you later read a property.useState()givesundefined. If you readuser.namebeforeuseris set, you get a TypeError. Start with a value of the same shape you will store, for examplenullplus a check, or an empty string. - Starting with a different type than you set later. If an input begins as
undefinedand later receives a string, React warns that it switched from uncontrolled to controlled. Begin with''.
Exercise
A component has const [count, setCount] = useState(10); and its parent re-renders it with different props, causing a second render. What does count equal on the second render if the user never clicked anything, and why? Then name what goes wrong if you write if (count > 5) { const [flag, setFlag] = useState(false); }.
Show answer
count is still 10. React uses the initial value only on the first render of that component instance and returns the stored value afterward, so changed props do not reseed it. The conditional useState breaks the Rules of Hooks. React matches Hook calls to stored state by call order, so when the condition changes between renders, later Hooks shift to the wrong slots and React throws an error or returns incorrect values. Call useState unconditionally and use the condition in the JSX or logic instead.