Sub topic 5
Custom Hooks for Reusable Logic
Prerequisites
This chapter assumes you can write function components with JSX and props, and that you know useState and useEffect well enough to read them. It also assumes you pass functions as props and use destructuring and ES modules.
What a custom hook is
A custom hook is a JavaScript function whose name starts with use and which calls other hooks inside it. It lets you move stateful logic out of a component and share it, without adding a component to the tree and without changing the markup.
Earlier patterns in this tutorial reuse structure (composition) or hand control to a caller (render props). A custom hook reuses only the logic. The component that calls it decides what to render.
Extracting logic from a component
Suppose several components need an on/off flag: a menu, a dialog, a disclosure. Each would repeat the same useState and the same flip function. Extract it once:
import { useCallback, useState } from 'react';
export function useToggle(initialOn = false) {
const [on, setOn] = useState(initialOn);
const toggle = useCallback(() => setOn((prev) => !prev), []);
const reset = useCallback(() => setOn(initialOn), [initialOn]);
return { on, toggle, reset };
}A component now consumes the hook and owns all of the markup:
import { useToggle } from './useToggle';
export function Menu() {
const { on: open, toggle } = useToggle();
return (
<div>
<button onClick={toggle} aria-expanded={open}>
Menu
</button>
{open && (
<ul>
<li>Profile</li>
<li>Settings</li>
</ul>
)}
</div>
);
}Two details are worth noting. toggle uses the functional form setOn((prev) => !prev), so it never reads a stale on value. And useCallback keeps the function identity stable between renders, which matters when the function is a dependency of an effect or is passed to a memoized child.
State is per call, not shared
A common misunderstanding is that two components calling useToggle() share one flag. They do not. Each call creates its own state, exactly as if you had written useState inline.
If you want components to see the same value, the state must live in a common parent (lifting state up) or in a context. A hook is a way to reuse the code that manages state. It does not reuse the state itself.
A hook that owns an effect
Hooks are most useful when they bundle state with an effect and its cleanup. This hook returns a value that only updates after the input has stopped changing for delay milliseconds:
import { useEffect, useState } from 'react';
export function useDebouncedValue(value, delay = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}Each time value changes, the cleanup function cancels the previous timer before a new one starts. A caller can use it like this:
import { useState } from 'react';
import { useDebouncedValue } from './useDebouncedValue';
export function SearchBox() {
const [text, setText] = useState('');
const settled = useDebouncedValue(text, 400);
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<p>Searching for: {settled}</p>
</div>
);
}The caller never sees a timer, a cleanup function, or a dependency array. That is the main benefit: a tricky effect is written and tested once.
Rules and common errors
React enforces two rules for hooks, and a linter (the react-hooks ESLint plugin) checks them.
- Call hooks only at the top level of a component or another hook. Not inside loops, conditions, or nested functions.
- Call hooks only from function components or other custom hooks.
The use prefix is how the linter knows a function is a hook. If you name useToggle as toggleState, the rules stop being checked for it.
The errors that appear most often in practice:
- Missing dependencies. An effect inside a hook reads
delaybut the dependency array omits it. The effect keeps using the first value. Fix the array instead of silencing the lint warning. - Unstable returned objects.
return { on, toggle }creates a new object on every render. That is fine for most callers. It breaks memoization if the caller puts the whole object in a dependency array. Destructure first, or wrap the result inuseMemowhen you publish a hook for others. - Unstable function arguments. Passing an inline callback into a hook that uses it as an effect dependency re-runs that effect on every render. Document that callers should memoize it, or store the latest callback in a ref inside the hook.
- Doing too much. A hook that returns fifteen values and takes ten options is a component in disguise. Split it into smaller hooks that compose.
Hooks compared with render props and higher-order components
All three patterns reuse logic. The difference is how the logic reaches the component.
| Pattern | How logic arrives | Cost |
|---|---|---|
| Render prop | A function child receives state | Extra nesting in JSX |
| Higher-order component | A wrapper injects props | Prop name collisions, harder to trace |
| Custom hook | A function call returns values | Cannot render markup itself |
Hooks add no wrapper components and no extra nesting, and they compose by calling one hook from another. Their limit is that a hook cannot produce structure. When the reusable part includes markup or coordination between several child components, a hook alone is not enough. That is where compound components come in, which later chapters cover.
Where hooks lead next
A hook that only returns { on, toggle } forces callers to wire handlers and accessibility attributes by hand, and it fixes the rules for how state changes. Two refinements address this. Prop getters return ready-to-spread props that merge a caller's handlers with the hook's own. The state reducer pattern lets a caller override how state transitions behave. Both build directly on the custom hook shape shown here, and both are covered in their own chapters.
Exercise
A teammate writes a hook useCounter() and calls it in both Header and Footer, expecting the two components to show the same count. The counts diverge. Why does this happen, and what are two ways to make them agree?
Show answer
Each call to useCounter() runs its own useState, so Header and Footer each get independent state. A hook reuses logic, not state. To share one count, either lift the state into a common parent that calls useCounter() once and passes the value and updater down as props, or put the state in a context provider that both components read from.
Exercise
This hook has a bug: export function useInterval(callback, ms) { useEffect(() => { const id = setInterval(callback, ms); return () => clearInterval(id); }, [ms]); }. What goes wrong when the caller passes a new inline callback each render, and how can you fix it?
Show answer
The dependency array omits callback, so the interval keeps calling the first callback it received, which can hold stale state. Adding callback to the array fixes staleness but resets the timer on every render when the callback is inline. The better fix is to store the latest callback in a ref, update ref.current on each render, have the interval call ref.current(), and keep [ms] as the only dependency.