A Custom Hook is a JavaScript function whose name starts with use and that calls built-in React Hooks such as useState, useEffect, or useRef. Custom Hooks let you extract duplicated logic—like debouncing search queries, syncing localStorage, or tracking online status—into one clean, testable module.
useDebounce HookEach component that calls a Custom Hook receives its own isolated state and effects. Calling useDebounce inside two different search inputs never mixes their values together.
import { useEffect, useState } from 'react';
export function useDebounce(value, delayMs = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(timer);
}, [value, delayMs]);
return debounced;
}
export function PackageSearch() {
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, 400);
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search packages..." />
<p>Searching API for: {debouncedQuery}</p>
</div>
);
}
use: Naming a hook useWindowSize instead of getWindowSize enables React's ESLint rules to check hook order inside your function.useDebounce), a tuple [value, setValue] when mirroring useState, or a named object { data, error, isLoading } when returning three or more fields.useCounter(), each component owns an independent counter. Use Context or a store to share data across components.use...: If a function does not call any React Hooks (like formatting dates), give it a normal verb name such as formatDate rather than useFormatDate.Yes. Composing smaller hooks inside larger ones—such as calling useLocalStorage inside useTheme—is one of React's strongest composition patterns.
Yes. Custom Hooks are ordinary JavaScript functions, so they can accept any parameters and return any JSX-friendly values or handlers.
Use @testing-library/react's renderHook utility to mount the hook in isolation and assert state changes cleanly.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With