Implement It from Scratch: 4 Essential Custom React Hooks for Interviews
Live-coding rounds for front-end roles (0–5 years of experience) often ask you to build custom React hooks from scratch. Interviewers use these problems to evaluate your grasp of React's render and commit phases, stale closures, effect cleanup, TypeScript generics, and browser APIs.
This guide walks through four high-frequency custom hooks: useDebounce, useOnClickOutside, useIntersectionObserver, and useAsync.
Question Index
| # | Hook | Core Pattern | Difficulty |
|---|---|---|---|
| 1 | useDebounce | Timer scheduling & cleanup | Medium |
| 2 | useOnClickOutside | Capture-phase DOM delegation | Medium |
| 3 | useIntersectionObserver | Browser Observer API & SSR safety | Medium-Hard |
| 4 | useAsync | Async state machine & AbortController | Hard |
1. Implement useDebounce
Requirements
- Create
useDebounce<T>(value: T, delay: number): Tthat delays updating the returned value untildelaymilliseconds pass withoutvaluechanging. - Cancel any pending timeout when
valueordelaychanges or when the component unmounts. - Preserve full TypeScript generic type inference for any input type
T.
Clarifying Questions to Ask the Interviewer
- Leading vs. trailing: Should the initial value be returned immediately on mount, with updates debounced on the trailing edge? (Yes, return
valueimmediately on mount and debounce subsequent changes.) - Zero or negative delay: Should
delay <= 0bypasssetTimeout? (UsingMath.max(0, delay)safely schedules a macrotask without unexpected behavior.)
Approach
- Initialize
debouncedValuestate withvalueviauseState<T>(value). - In
useEffect, schedule asetTimeoutthat updatesdebouncedValueafterdelayms. - Return a cleanup function calling
clearTimeout(timer)so rapid updates reset the timer and unmount leaves no dangling timers.
Implementation
import { useEffect, useState } from 'react';
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value);
}, Math.max(0, delay));
return () => {
clearTimeout(timer);
};
}, [value, delay]);
return debouncedValue;
}
Edge Cases Handled
- Component unmount: Cleanup clears the active timer so
setDebouncedValueis never called after unmount. - Dynamic delay: Including
delayin the dependency array restarts the timer cleanly if the caller changes the delay. - Object references: Callers passing inline objects should memoize them with
useMemoso reference changes do not re-trigger the effect.
Complexity
- Time: $O(1)$ per render and timer tick.
- Space: $O(1)$ for one state slot and one timer ID.
Usage Example
function ProductSearch() {
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, 300);
useEffect(() => {
if (debouncedQuery) {
fetch(`/api/products?q=${encodeURIComponent(debouncedQuery)}`);
}
}, [debouncedQuery]);
return <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search..." />;
}
Likely Follow-ups
- "How would you implement
useDebouncedCallbackwith.cancel()and.flush()methods without stale closures?" - "What is the difference between debouncing and throttling, and when would you choose each?"
2. Implement useOnClickOutside
Requirements
- Detect
mousedownandtouchstartevents occurring outside a target DOM element (or list of elements). - Support an array of refs so a trigger button and a portaled menu can both be treated as "inside".
- Always invoke the latest
handlerwithout detaching and re-attaching document listeners on every render.
Clarifying Questions to Ask the Interviewer
- Event type: Should we listen to
clickormousedown/touchstart? (mousedownandtouchstartfire before focus shifts and handle mobile devices.) - Event phase: Capture or bubbling? (Capture phase catches outside clicks even if an inner element calls
stopPropagation().)
Approach
- Store
handlerin auseRefupdated viauseEffectso the event listener stays stable. - Attach capture-phase
mousedownandtouchstartlisteners todocument. - Inside the listener, verify
target.isConnectedand check whether any ref's.currentcontainstarget. If none do, callhandlerRef.current(event).
Implementation
import { RefObject, useEffect, useRef } from 'react';
type PointerEventType = MouseEvent | TouchEvent;
export function useOnClickOutside<T extends HTMLElement = HTMLElement>(
refs: RefObject<T | null> | Array<RefObject<T | null>>,
handler: (event: PointerEventType) => void
): void {
const handlerRef = useRef(handler);
useEffect(() => {
handlerRef.current = handler;
}, [handler]);
useEffect(() => {
const listener = (event: PointerEventType) => {
const target = event.target as Node | null;
if (!target || !target.isConnected) return;
const refList = Array.isArray(refs) ? refs : [refs];
const clickedInside = refList.some((r) => r.current?.contains(target));
if (!clickedInside) {
handlerRef.current(event);
}
};
document.addEventListener('mousedown', listener, true);
document.addEventListener('touchstart', listener, true);
return () => {
document.removeEventListener('mousedown', listener, true);
document.removeEventListener('touchstart', listener, true);
};
}, [refs]);
}
Edge Cases Handled
- Detached DOM nodes: If clicking an item inside the menu immediately unmounts that item before the document listener runs,
target.isConnectedisfalse, preventing a false outside-click trigger. - Portals and triggers: Passing
[menuRef, buttonRef]prevents clicking the toggle button from closing and immediately reopening the menu.
Complexity
- Time: $O(K \times D)$ per click, where $K$ is the number of refs and $D$ is DOM tree depth for
.contains(). - Space: $O(1)$ for two document listeners.
Usage Example
function Dropdown() {
const [open, setOpen] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
useOnClickOutside([menuRef, buttonRef], () => setOpen(false));
return (
<div>
<button ref={buttonRef} onClick={() => setOpen((o) => !o)}>Menu</button>
{open && <div ref={menuRef}>Dropdown Items</div>}
</div>
);
}
Likely Follow-ups
- "Why might an inline array
[menuRef, buttonRef]cause unnecessary effect re-runs, and how would you stabilize it?" - "What happens if the user clicks inside a cross-origin
iframe?"
3. Implement useIntersectionObserver
Requirements
- Track when a target element enters or exits the viewport (or custom scroll root) using
IntersectionObserver. - Support a
freezeOnceVisibleoption that disconnects the observer after the element becomes visible once. - Guard against Server-Side Rendering (SSR) where
windoworIntersectionObserveris undefined.
Clarifying Questions to Ask the Interviewer
- Return shape: Should the hook return a boolean
isIntersectingor the fullIntersectionObserverEntry | null? (ReturningIntersectionObserverEntry | nullgives callers bothisIntersectingandintersectionRatio.) - Threshold arrays: Should inline
threshold: [0, 0.5, 1]work without recreating the observer every render? (Yes, serializethresholdor memoize options.)
Approach
- Store
entryin state (nullinitially) and trackfrozenin auseRef(false). - In
useEffect, exit early iftypeof window === 'undefined',!('IntersectionObserver' in window),!targetRef.current, orfrozen.current. - Create the observer, observe
targetRef.current, and disconnect in the cleanup function (or immediately oncefreezeOnceVisibleis satisfied).
Implementation
import { RefObject, useEffect, useRef, useState } from 'react';
export interface UseIntersectionOptions extends IntersectionObserverInit {
freezeOnceVisible?: boolean;
}
export function useIntersectionObserver(
targetRef: RefObject<Element | null>,
{ threshold = 0, root = null, rootMargin = '0px', freezeOnceVisible = false }: UseIntersectionOptions = {}
): IntersectionObserverEntry | null {
const [entry, setEntry] = useState<IntersectionObserverEntry | null>(null);
const frozen = useRef(false);
const serializedThreshold = JSON.stringify(threshold);
useEffect(() => {
const node = targetRef.current;
const supported = typeof window !== 'undefined' && 'IntersectionObserver' in window;
if (!supported || !node || frozen.current) return;
const observer = new IntersectionObserver(
([firstEntry]) => {
setEntry(firstEntry);
if (firstEntry.isIntersecting && freezeOnceVisible) {
frozen.current = true;
observer.disconnect();
}
},
{ threshold, root, rootMargin }
);
observer.observe(node);
return () => observer.disconnect();
}, [targetRef, root, rootMargin, serializedThreshold, freezeOnceVisible]);
return entry;
}
Edge Cases Handled
- SSR safety: Checking
typeof window !== 'undefined'avoidsReferenceErrorduring Next.js or Remix server rendering. - Unstable threshold arrays: Serializing
thresholdprevents infinite observer teardown/recreation when callers pass inline arrays.
Complexity
- Time: $O(1)$ setup; intersection math runs asynchronously off the main thread in the browser.
- Space: $O(1)$ per observed element.
Usage Example
function LazyCard({ src, alt }: { src: string; alt: string }) {
const cardRef = useRef<HTMLDivElement>(null);
const entry = useIntersectionObserver(cardRef, { rootMargin: '150px', freezeOnceVisible: true });
return (
<div ref={cardRef} style={{ minHeight: 200 }}>
{entry?.isIntersecting ? <img src={src} alt={alt} /> : <span>Loading...</span>}
</div>
);
}
Likely Follow-ups
- "How would you use this hook to build infinite-scroll pagination?"
- "Why is
IntersectionObserverpreferred overscrollevent listeners withgetBoundingClientRect()?"
4. Implement useAsync
Requirements
- Manage asynchronous execution states:
'idle' | 'pending' | 'success' | 'error'. - Return
{ status, data, error, isLoading, execute, reset }. - Prevent race conditions and post-unmount state updates using
AbortController.
Clarifying Questions to Ask the Interviewer
- Auto-run: Should
asyncFnrun automatically on mount or only whenexecute()is called? (Support animmediate = falseflag.) - Previous data: Should
databe cleared when a new request starts? (Keep previousdatato avoid UI flicker unlessreset()is called.)
Approach
- Hold the latest
asyncFnin auseRefsoexecutemaintains a stable reference across renders. - Hold the active
AbortControllerin a ref; abort any in-flight request before starting a new one or on unmount. - Pass
controller.signalintoasyncFnand check!controller.signal.abortedbefore updating React state.
Implementation
import { useCallback, useEffect, useRef, useState } from 'react';
export type AsyncStatus = 'idle' | 'pending' | 'success' | 'error';
export function useAsync<T, E = Error>(
asyncFn: (signal: AbortSignal, ...args: any[]) => Promise<T>,
immediate = false
) {
const [status, setStatus] = useState<AsyncStatus>('idle');
const [data, setData] = useState<T | null>(null);
const [error, setError] = useState<E | null>(null);
const fnRef = useRef(asyncFn);
const controllerRef = useRef<AbortController | null>(null);
useEffect(() => {
fnRef.current = asyncFn;
}, [asyncFn]);
const reset = useCallback(() => {
controllerRef.current?.abort();
controllerRef.current = null;
setStatus('idle');
setData(null);
setError(null);
}, []);
const execute = useCallback(async (...args: any[]): Promise<T | null> => {
controllerRef.current?.abort();
const controller = new AbortController();
controllerRef.current = controller;
setStatus('pending');
setError(null);
try {
const result = await fnRef.current(controller.signal, ...args);
if (!controller.signal.aborted) {
setData(result);
setStatus('success');
return result;
}
return null;
} catch (err) {
if (!controller.signal.aborted) {
setError(err as E);
setStatus('error');
}
return null;
} finally {
if (controllerRef.current === controller) {
controllerRef.current = null;
}
}
}, []);
useEffect(() => {
if (immediate) execute();
return () => controllerRef.current?.abort();
}, [execute, immediate]);
return {
status,
data,
error,
isLoading: status === 'pending',
execute,
reset,
};
}
Edge Cases Handled
- Race conditions: Rapidly calling
execute()aborts the prior request so slower responses never overwrite newer results. - Unmount cleanup: Unmounting aborts the active
AbortController, preventing stale state updates.
Complexity
- Time: $O(1)$ hook state overhead; total time is bounded by the async operation.
- Space: $O(1)$ for controller ref, status, and response payload.
Usage Example
function ProfileCard({ userId }: { userId: string }) {
const { data, error, isLoading, execute } = useAsync(
(signal) => fetch(`/api/users/${userId}`, { signal }).then((r) => r.json())
);
return (
<div>
<button onClick={() => execute()} disabled={isLoading}>Load Profile</button>
{error && <p>{error.message}</p>}
{data && <h3>{data.name}</h3>}
</div>
);
}
Likely Follow-ups
- "How does
useAsynccompare to TanStack Query or SWR for caching and deduplication?" - "How would you handle functions that don't natively accept an
AbortSignal?"
Preparation Checklist
- Cleanup everything: Always return teardown functions for timers, listeners, observers, and
AbortControllerinstances. - Stabilize callbacks with refs: Store changing callback props in
useRefto avoid tearing down listeners or resetting timers. - Guard SSR: Check
typeof window !== 'undefined'before touching browser-only globals likeIntersectionObserver. - Prevent race conditions: Cancel or ignore stale async responses whenever inputs change or components unmount.
- Use TypeScript generics: Parameterize hook inputs and outputs with
<T>so consumers keep strict type safety.
Conclusion
Custom React hooks test whether you understand React's execution lifecycle, closure scoping, and browser resource cleanup. Implementing useDebounce, useOnClickOutside, useIntersectionObserver, and useAsync cleanly from scratch demonstrates production-ready front-end engineering judgment.