Update state from the previous value
setCount((c) => c + 1);
Two plain setCount(count + 1) calls in one handler both read the same count and add one.
The hooks and patterns that carry most React components, from effects that clean up after themselves to keys, transitions, and lazy routes.
setCount((c) => c + 1);
Two plain setCount(count + 1) calls in one handler both read the same count and add one.
const timer = useRef<number | null>(null);
Changing timer.current doesn’t render. Use state for anything the UI shows.
<Editor key={docId} />
A new key unmounts the old instance and mounts a fresh one, so every useState inside starts over.
<input value={name} onChange={(e) => setName(e.target.value)} />
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []);
Strict Mode runs the effect twice in development, so the cleanup has to undo the setup completely.
const sorted = useMemo(() => [...items].sort(byName), [items]);
const onSave = useCallback(() => save(draft), [draft]);
Only worth it when the child is wrapped in memo or the function is an effect dependency.
{users.map((u) => <UserRow key={u.id} user={u} />)}
The index as a key breaks as soon as the list reorders or an item is removed.
const ThemeContext = createContext<Theme>("light");
const theme = useContext(ThemeContext);
Every consumer re-renders when the provider’s value changes, so keep the value small.
function Card({ children }: { children: ReactNode }) {
return <div className="card">{children}</div>;
}
const Editor = lazy(() => import("./editor"));
<Suspense fallback={<Spinner />}>
<Editor />
</Suspense>
The import becomes its own chunk. The fallback shows until it arrives.
const [isPending, startTransition] = useTransition();
startTransition(() => setQuery(input));
The update inside the transition can be interrupted by the next keystroke. isPending is true until it lands.
<form action={async (formData) => { await save(formData.get("title")); }}>
React 19 resets the form after the action resolves and tracks the pending state for useFormStatus.