Custom Hooks: Extracting Reusable Logic
How to build and name custom hooks, and what makes them testable and reusable.
On this page
30‑second interview answer
A custom hook is just a function that uses React hooks to encapsulate reusable stateful logic. It must follow the Rules of Hooks and is typically named useSomething. Custom hooks help keep components clean by separating UI from logic and enable reuse across components.
Why custom hooks matter
They let you:
- reuse logic without copying code
- keep UI components focused on rendering
- isolate side-effects
Think: “extract logic, not JSX.”
Example: useDebouncedValue
function useDebouncedValue(value, delayMs) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(id);
}, [value, delayMs]);
return debounced;
}Usage:
const debouncedQuery = useDebouncedValue(query, 300);Rules of Hooks still apply
- Call hooks at the top level
- Don’t call hooks conditionally
- Custom hooks can call other hooks
Designing good custom hooks
1) Keep the API small
Return what consumers need. Prefer:
valueactions
Example:
return { data, loading, error, refetch };2) Separate logic from presentation
Your hook shouldn’t return JSX.
3) Make effects cancellable
For async work, avoid setting state after unmount (AbortController or cancellation flags).
Interview traps
“Is a custom hook a component?”
No. It doesn’t render UI.
“Why not just a utility function?”
Utilities are great, but hooks manage React state/effects and integrate with lifecycle.
Testing custom hooks
Approaches:
- test via a component that uses the hook
- or use a hook-testing utility (library choice)
The key is: the hook should be deterministic based on inputs and side effects should be controlled.
Mini Q&A
Q1: What is a custom hook?
- A function that uses hooks to encapsulate reusable logic.
Q2: Why prefix with use?
- So lint rules can enforce Rules of Hooks.
Q3: What should a custom hook return?
- A small API: state + actions.
Summary checklist
- I can explain custom hooks clearly.
- I follow the Rules of Hooks.
- I can build a hook with cleanup.
- I keep UI separate.
Looking for structured, offline interview prep?
Free online lessons • Portable Amazon Kindle / Paperback
Frontend Interview Guide (2025 Edition)
By Rajesh Dhiman
Comprehensive preparation covering React internals, Web Performance, CSS architecture, and system design questions.
JavaScript Interview Guide
By Rajesh Dhiman
Deep dive into the Event Loop, microtask draining, closures, prototypal inheritance, and asynchronous execution patterns.
Note: All lessons on Frontend Interview remain completely free to read online. As an Amazon Associate, we may earn from qualifying purchases.
Written by Rajesh Dhiman
Authored by Rajesh Dhiman and engineered at Eunix Tech. Focused on deep-dive frontend engineering, JavaScript runtime internals, React architecture, and web performance.