What You'll Learn
- 1State the two hook rules and explain what breaks when either is violated
- 2Decide between useState and useReducer from the shape of the update logic
- 3Write an effect that cancels in-flight work instead of applying late responses
- 4Recognise a stale closure and fix it with a functional update or a ref
Why hooks landed in function components
Before hooks, stateful logic lived in class components: componentDidMount for setup, componentDidUpdate for reaction, componentWillUnmount for teardown, and this everywhere in between. That split had a real cost. Logic that belonged together, such as subscribing to a socket and unsubscribing when the room changed, was scattered across three methods, and there was no way to share any of it between components without inventing a wrapper component or a higher-order component.
Hooks let a function component declare its own state and side effects directly. The deeper win is composition. A hook is just a function that calls other hooks, so a piece of stateful behaviour can be extracted into a file, imported by two components, and tested on its own. The component tree stays flat, and reuse happens at the level of logic rather than markup.
The two rules and why they exist
React relies on hooks being called in the same order on every render so it can line up each hook call with its stored state. That gives you two hard rules: only call hooks at the top level of a component or another hook, never inside loops, conditions, or nested functions; and only call hooks from React function components or from custom hooks, never from plain utilities or event handlers.
Breaking the first rule changes the number of hook calls between renders. React then reads state from the wrong slot, so a value from one hook appears where another belongs. This is not a style guideline the compiler is fussing about, it is the data structure. Conditional hooks look harmless:
// WRONG: the early return means useState runs only on some renders
function FilterableList({ items }) {
const [query, setQuery] = useState('');
if (!items.length) return <Empty />;
const [selected, setSelected] = useState(null); // slot shifts between renders
return <List items={items} query={query} selected={selected} />;
}
The fix is to always declare the hooks and then decide what to render:
function FilterableList({ items }) {
const [query, setQuery] = useState('');
const [selected, setSelected] = useState(null);
if (!items.length) return <Empty />;
return <List items={items} query={query} selected={selected} />;
}
The eslint plugin react-hooks knows these rules and reports violations at edit time. Turning that rule off hides real corruption bugs, so keep it on.
Choosing between useState and useReducer
Both store state; they differ in how updates are expressed. The right question is whether the next value depends on the previous one in more than one way.
| Situation | Prefer | Reason |
|---|---|---|
| One scalar: a boolean, a string, a number | useState | The update is a direct assignment, nothing to organise |
| Several values that always change together | useReducer | One state object stays consistent across related fields |
| Next value depends on the previous one | useReducer or a functional updater | Avoids reading a value captured in an old render |
| Many actions on the same data | useReducer | The action type documents intent in one place |
| State is passed to a deep child | useReducer with context | Dispatch is stable, so splitting providers stays simple |
A reducer also gives you a free audit trail. Every change arrives as an action object, which is easy to log, replay in tests, and reason about when the bug report says the screen showed something impossible.
Fetching that cancels itself
The most common hook bug is a response arriving after the component has moved on: you switch from user 7 to user 8, and the slower request for 7 lands last, overwriting the correct data. Effects must therefore pair setup with teardown.
function Profile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
setError(null);
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
})
.then(setUser)
.catch((err) => {
if (err.name !== 'AbortError') setError(err);
});
return () => controller.abort();
}, [userId]);
if (error) return <p role="alert">{error.message}</p>;
if (!user) return <p>Loading profileβ¦</p>;
return <h1>{user.name}</h1>;
}
The cleanup function runs before the effect re-fires and on unmount, so exactly one request is live at a time. In React 18 StrictMode, effects intentionally run twice in development to prove your cleanup works; if you see two requests in dev, the abort path is missing rather than the framework being broken.
Refs: a box that outlives render
useRef returns the same object on every render, and writing to its current property does not schedule anything. That makes it the right tool for values that are not part of the UI: timers, subscription handles, previous values, and the DOM node you need to focus.
function useDebouncedValue(value, delay) {
const [debounced, setDebounced] = useState(value);
const timer = useRef(null);
useEffect(() => {
timer.current = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(timer.current);
}, [value, delay]);
return debounced;
}
Note the division of labour: the ref holds infrastructure that never needs to render, while state holds the value the screen displays. Reaching for a ref when a value should appear in the UI is how components end up rendering stale content that never updates.
Stale closures, and how to spot one
Every render creates its own closure with its own copy of the variables in scope. An effect declared on the first render keeps that copy forever if its dependency array is empty, so a handler inside it reads the value the component had on mount rather than the value it has now. The symptom is a counter that always adds one to zero, a form that submits the first email typed, or a socket listener that logs an outdated id.
Three reliable repairs: depend on the value by listing it in the array; use the functional updater form of a setter when only the previous state matters; or keep the mutable value in a ref and read it through ref.current inside the effect. Each one restores access to the current value without forcing the effect to re-run more often than it should.
When state should move out of the component
Hooks keep state local by default, which is the right starting point, but a component that grows a long list of setters is usually telling you the state has moved. Consider a checkout screen where the selected address, the chosen shipping speed, and the applied coupon each live in a different sibling panel yet all feed one summary. Pushing that state to the nearest common parent removes the awkward upward callbacks and gives the summary a single source to read.
When the common ancestor is the application root, lifting stops being attractive: every intermediate component re-renders and the prop list becomes noise. That is the moment to reach for context, which lets distant consumers read a value without drilling it through, or for an external store such as Zustand when several unrelated trees need the same slice. The escalation path is short and worth following in order: local state first, then lifted state, then context for values that change infrequently, then a store for values that change often and are read widely.
One warning applies at every level: state that is duplicated in two places will eventually disagree. If a value can be computed from other state, do not store it. If it is stored in one place, never copy it into another for convenience. Keeping a single owner for each piece of data is what makes hook-heavy code predictable as the screen expands.
Common Mistakes
Calling a hook after an early return or inside a loop so hook order changes between renders
Fix: Declare every hook unconditionally at the top, then branch on what to render
Listing no dependencies so the effect reads values captured on the first render
Fix: List every value the effect reads, or use a functional update or ref for purely mutable data
Firing a fetch in an effect without a cleanup, letting a slow response overwrite fresh data
Fix: Return a cleanup that aborts the request or ignores the late result
Copying state into a second useState that must be kept in sync by hand
Fix: Derive the second value during render, or move both into a single reducer state object
Best Practices
- Keep the eslint react-hooks rules enabled in every project
- Prefer the functional updater whenever the next state is computed from the current one
- Name custom hooks starting with use and give each one a single responsibility
- Log the effect dependency array when debugging: it is the contract that explains when setup repeats
- Put values that never render, such as timer handles, in refs rather than state
Key Takeaways
- Hook order is a data structure: call hooks unconditionally and only from components or hooks
- useReducer suits multi-field state and multi-action updates; useState suits single scalars
- Every effect that acquires a resource must return the code that releases it
- Stale closures come from renders that no longer run, and dependencies, updaters, or refs fix them
- Refs hold infrastructure; state holds anything the screen must display