Sub topic 2
Declaring state with useState
This chapter assumes you know JavaScript destructuring and arrow functions, can write a JSX function component, and know how props work. It covers the useState call itself. Re-rendering, snapshots, and updater functions get their own chapters.
Why a local variable fails
A component is a function that React calls on every render. A plain let count = 0 inside it is recreated on each call, so any change to it is lost. Changing it also does not tell React to redraw anything. State fixes both problems. React stores the value outside your function, hands it back on the next render, and re-renders when you update it.
The useState call
useState takes an initial value and returns a two-item array: the current value and a setter function.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}Array destructuring lets you choose the names. The usual convention is [thing, setThing].
countis the value for the current render. On the first render it is0.setCount(next)stores a new value and asks React to render the component again.- The initial value is used only on the first render. Later renders ignore the argument.
Rules for calling it
React matches each useState call to its stored value by call order. For that reason, Hooks follow two rules.
- Call Hooks only at the top level of a component or custom Hook. Do not put them inside
ifstatements, loops, or nested functions. - Call them only from function components or other Hooks.
Several state variables
A component can call useState as many times as it needs. Each call is independent.
import { useState } from 'react';
function Signup() {
const [email, setEmail] = useState('');
const [agreed, setAgreed] = useState(false);
return (
<form>
<input value={email} onChange={e => setEmail(e.target.value)} />
<input type="checkbox" checked={agreed} onChange={e => setAgreed(e.target.checked)} />
</form>
);
}State is private to each component instance. Two Counter components on one page each keep their own count.
Common mistakes
- Assigning directly, as in
count = count + 1. The screen does not update, and the value resets on the next render. - Reading the value right after calling the setter and expecting it to have changed. Your handler still sees the old value. The snapshot chapter explains why.
- Calling the setter during render.
setCount(1)in the component body causes a render loop.
Exercise
A component contains let clicks = 0; and a button whose handler runs clicks++. The number shown never changes. Give two reasons, then show the fix.
Show answer
First, changing a local variable does not tell React to re-render, so the screen is not redrawn. Second, even if a re-render happens for another reason, the function runs again and clicks is reset to 0. The fix is const [clicks, setClicks] = useState(0); with the handler calling setClicks(clicks + 1).