What is a custom hook, and why would you write one?
A custom hook is a function whose name starts with use and that calls other hooks. It lets you reuse stateful logic across components. Each component that calls it gets its own separate state.
Explain it simply
If five screens need the same steps (read a value from localStorage, keep it in state, save when it changes), copying the code five times invites bugs. A custom hook packs those steps into one function you call anywhere.
It shares logic, not state. Two components calling useLocalStorage("theme") each get their own state, just as two people using the same recipe cook separate pots.
The use prefix is a convention that matters: linters rely on it to check the rules of hooks inside the function.
A custom hook can also return nothing, a single value, an array or an object. Pick the shape that reads best at the call site, and keep the hook focused on one job so its name says what it does.
Example
function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
const saved = localStorage.getItem(key);
return saved ? JSON.parse(saved) : initial;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
const [theme, setTheme] = useLocalStorage("theme", "light");What to say in the interview
"A custom hook is a function starting with use that composes built-in hooks to package reusable logic. It shares behaviour, not state: every call creates independent state. I extract one when the same combination of state and effects appears in multiple components, or to make a component read more clearly."
Common mistakes
- Believing two components share state just because they call the same custom hook.