Lesson 170 of 296
Rules of hooks, custom hooks and stale closures
What you will learn
- The two rules of hooks, and why they exist
- Writing custom hooks
- useDebounce, useFetch and useLocalStorage from scratch
- Stale closures and how to fix them
On this page
The rules of hooks
- Only call hooks at the top level of a component or custom hook: never inside conditions, loops, nested functions, or after an early return.
- Only call hooks from React function components or custom hooks, not from normal functions or classes.
Why rule 1? React does not know hooks by name. It remembers them by the order they are called in each render: the first useState call is state number 1, the second is number 2, and so on. If a hook is inside an if, the order can change between renders, and React gives the wrong state to the wrong hook.
function Bad({ show }: { show: boolean }) {
if (show) {
const [a, setA] = useState(0); sometimes called, sometimes not: breaks the order
}
const [b, setB] = useState("");
}Fix: call the hook unconditionally and put the condition inside it or in the JSX. The ESLint plugin eslint-plugin-react-hooks enforces these rules.
Custom hooks
A custom hook is a function whose name starts with use and that calls other hooks. It lets you reuse stateful logic between components. Each component that calls it gets its own independent state.
useDebounce
Delays a fast-changing value (like search text) until it stops changing (Lesson 78):
function useDebounce<T>(value: T, delayMs: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(id);
}, [value, delayMs]);
return debounced;
}Each change of value cancels the previous timer in the clean-up, so the debounced value only updates after delayMs of quiet.
Usage:
function LiveSearch() {
const [text, setText] = useState("");
const query = useDebounce(text, 300);
return (
<>
<input aria-label="Search" value={text} onChange={(e) => setText(e.target.value)} />
<p>Searching for: {query}</p>
</>
);
}useFetch
A small data-fetching hook with loading, error, cancellation and a discriminated union (Lessons 107 and 166):
type FetchState<T> =
| { status: "loading" }
| { status: "error"; error: string }
| { status: "success"; data: T };
function useFetch<T>(url: string | null): FetchState<T> {
const [state, setState] = useState<FetchState<T>>({ status: "loading" });
useEffect(() => {
if (url === null) return;
const controller = new AbortController();
setState({ status: "loading" });
fetch(url, { signal: controller.signal })
.then(async (res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as T;
})
.then((data) => setState({ status: "success", data }))
.catch((err: unknown) => {
if (controller.signal.aborted) return;
setState({ status: "error", error: err instanceof Error ? err.message : "Unknown error" });
});
return () => controller.abort();
}, [url]);
return state;
}- Passing
nulllets callers skip fetching until they have a URL. - Aborting in the clean-up prevents race conditions and state updates after unmount.
- In an interview, mention what a real library adds: caching, de-duplication, retries, refetching on focus, and pagination (Lesson 174).
useLocalStorage
State that is saved to localStorage and survives a refresh (Lesson 90):
function useLocalStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
try {
const stored = localStorage.getItem(key);
return stored === null ? initialValue : (JSON.parse(stored) as T);
} catch {
return initialValue;
}
});
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// storage full or unavailable: keep working in memory
}
}, [key, value]);
return [value, setValue] as const;
}- Lazy initial state (Lesson 160) reads storage once.
try...catchhandles invalid JSON and unavailable storage.as constmakes the return type a tuple[T, setter], likeuseState, instead of an array of mixed types.- With server rendering (Part 13),
localStoragedoes not exist on the server; read it in an effect, or guard withtypeof window !== "undefined".
Stale closures
Every render creates new functions that close over (Lesson 53) that render's props and state. A function that is kept and called later still sees the values from its render: a stale closure.
function StaleCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1); count is always 0 here
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{count}</p>;
}The effect ran once, so its interval callback closed over count = 0 forever. The counter goes to 1 and stops.
Fixes:
| Fix | Code |
|---|---|
| Functional update (best here) | setCount((c) => c + 1) |
| Add the dependency | [count] (the interval restarts every second, which works but is wasteful) |
| Keep the latest value in a ref | latestRef.current = value in an effect, read latestRef.current in the callback |
| useEffectEvent (React 19.2) | Effect logic that always reads the latest values (Lesson 166) |
function WorkingCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => setCount((c) => c + 1), 1000);
return () => clearInterval(id);
}, []);
return <p>{count}</p>;
}How to say it in an interview
"Hooks must be called at the top level of components or custom hooks, never conditionally, because React identifies them by call order. Custom hooks start with use and reuse stateful logic; each caller gets independent state. I have written useDebounce with a timeout cleared in the cleanup, useFetch with AbortController and a status union, and useLocalStorage with lazy initialisation and try-catch. Stale closures happen when a callback created in an old render runs later with old values; I fix them with functional updates, correct dependencies, a ref holding the latest value, or useEffectEvent."
Key words
| Word | Meaning |
|---|---|
| Rules of hooks | Call hooks only at the top level of components or custom hooks |
| Custom hook | A use... function that combines other hooks |
| Stale closure | A function using old values from the render it was created in |
| as const | Makes a returned array a fixed tuple type |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.