State (useState)
State is a value a component owns and can change. useState returns the current value plus a setter; setting it re-renders the component with the new value.
useState patterns
EXAMPLE
import { useState } from 'react';
// Primitive state
function Counter() {
const [n, setN] = useState(0);
return <button onClick={() => setN(n + 1)}>{n}</button>;
}
// Object state — REPLACE, don't mutate
function Profile() {
const [user, setUser] = useState({ name: '', age: 0 });
return <input value={user.name}
onChange={e => setUser({ ...user, name: e.target.value })} />;
}
// Updater form — when the new state depends on the previous
function DoubleClick() {
const [n, setN] = useState(0);
return <button onClick={() => { setN(p => p + 1); setN(p => p + 1); }}>{n}</button>;
// Plain setN(n+1) twice would still only bump by 1.
}
// Lazy initialiser — runs ONCE
const [items, setItems] = useState(() => JSON.parse(localStorage.items ?? '[]'));
Why it matters
Never mutate state in place. React decides whether to re-render by reference equality — obj.x = 1 on the same object means React sees no change and skips the render.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
import { useState } from 'react';
function Counter() {
const [n, setN] = useState(0);
return <button onClick={() => setN(n + 1)}>Clicked {n}</button>;
}
Try it Yourself »
Exercise
Local state hook.
const [n, setN] =
(0);
camelCase; eight chars.
Discussion
Loading…