React Custom Hooks
When two components need the same stateful logic — tracking the window size, syncing with localStorage, debouncing an input — you can extract that logic into your own hook. A custom hook is simply a function whose name starts with use and that calls other hooks.
Extracting a hook
Imagine several components need to know whether the user is online. Instead of repeating a state variable and an effect in each, move them into useOnlineStatus:
import { useEffect, useState } from 'react';
function useOnlineStatus() {
const [online, setOnline] = useState(navigator.onLine);
useEffect(() => {
const goOnline = () => setOnline(true);
const goOffline = () => setOnline(false);
window.addEventListener('online', goOnline);
window.addEventListener('offline', goOffline);
return () => {
window.removeEventListener('online', goOnline);
window.removeEventListener('offline', goOffline);
};
}, []);
return online;
}
function StatusBar() {
const online = useOnlineStatus();
return <p>{online ? '🟢 Online' : '🔴 Offline — changes will sync later'}</p>;
}
function SaveButton() {
const online = useOnlineStatus();
return <button disabled={!online}>{online ? 'Save' : 'Reconnecting…'}</button>;
}
export default function App() {
return (
<div>
<StatusBar />
<SaveButton />
<p><small>Toggle "Offline" in your DevTools Network tab to test.</small></p>
</div>
);
}Each component that calls the hook gets its own state and effect. Hooks share logic, never state — to share state, lift it up or use context.
A hook with parameters and return values
Custom hooks can take arguments and return anything: a value, an array like useState, or an object.
import { useEffect, useState } from 'react';
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const saved = localStorage.getItem(key);
return saved !== null ? JSON.parse(saved) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// storage may be unavailable (private mode, sandboxed frames)
}
}, [key, value]);
return [value, setValue];
}
export default function App() {
const [name, setName] = useLocalStorage('demo-name', '');
const [fontSize, setFontSize] = useLocalStorage('demo-font', 16);
return (
<div style={{ fontSize }}>
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" />{' '}
<button onClick={() => setFontSize(fontSize + 2)}>A+</button>{' '}
<button onClick={() => setFontSize(16)}>reset</button>
<p>Hello, {name || 'stranger'}! Run this example again — your values are remembered (if storage is available).</p>
</div>
);
}The component reads like it uses plain useState, while persistence is hidden inside the hook.
Debouncing
A debounced value only updates after the input has been quiet for a while — perfect for search boxes that shouldn't query on every keystroke:
import { useEffect, useState } from 'react';
function useDebounce(value, delay = 500) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id); // a new keystroke cancels the pending update
}, [value, delay]);
return debounced;
}
const CITIES = ['Amsterdam', 'Bangkok', 'Berlin', 'Cairo', 'Hanoi', 'Hue', 'Lisbon', 'London', 'Lima', 'Madrid', 'Seoul', 'Sydney'];
export default function App() {
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, 400);
const results = debouncedQuery ? CITIES.filter((c) => c.toLowerCase().includes(debouncedQuery.toLowerCase())) : [];
useEffect(() => {
if (debouncedQuery) console.log('searching:', debouncedQuery);
}, [debouncedQuery]);
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search cities" />
<p><small>typed: "{query}" · searched: "{debouncedQuery}"</small></p>
<ul>{results.map((c) => <li key={c}>{c}</li>)}</ul>
</div>
);
}A toggle and a fetch-like hook
Hooks can also wrap async work. This one simulates a request and returns { data, loading, error }:
import { useCallback, useEffect, useState } from 'react';
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((v) => !v), []);
return [on, toggle];
}
const fakeApi = (page) =>
new Promise((resolve, reject) =>
setTimeout(() => (page > 3 ? reject(new Error('No more pages')) : resolve([`Item ${page}a`, `Item ${page}b`])), 600)
);
function useAsync(fn, deps) {
const [state, setState] = useState({ data: null, loading: true, error: null });
useEffect(() => {
let ignore = false;
setState({ data: null, loading: true, error: null });
fn().then(
(data) => !ignore && setState({ data, loading: false, error: null }),
(error) => !ignore && setState({ data: null, loading: false, error })
);
return () => { ignore = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
return state;
}
export default function App() {
const [page, setPage] = useState(1);
const [details, toggleDetails] = useToggle();
const { data, loading, error } = useAsync(() => fakeApi(page), [page]);
return (
<div>
<button onClick={() => setPage(page - 1)} disabled={page === 1}>◀</button> Page {page}{' '}
<button onClick={() => setPage(page + 1)}>▶</button>{' '}
<button onClick={toggleDetails}>{details ? 'Hide' : 'Show'} details</button>
{loading && <p>Loading…</p>}
{error && <p style={{ color: 'crimson' }}>Error: {error.message}</p>}
{data && <ul>{data.map((d) => <li key={d}>{d}{details && ` (from page ${page})`}</li>)}</ul>}
</div>
);
}Guidelines
| Do | Don't |
|---|---|
Name it useSomething |
name a plain helper useX if it calls no hooks |
Give it one clear purpose (useDebounce, useMediaQuery) |
build vague "lifecycle" hooks like useMount |
Return stable functions (useCallback) when callers may depend on them |
expect two components to share state through a hook |
| Follow the rules of hooks inside it | call hooks conditionally inside it |
Tip: Popular libraries are mostly collections of custom hooks —
useQueryfrom TanStack Query,useNavigatefrom React Router,useFormfrom React Hook Form. Once you can write your own, their APIs feel natural.
Test yourself
Two components call useOnlineStatus(). Do they share the same state variable?
- Yes, hooks share state
- No, each call has its own independent state
- Only if they are siblings
- Only in production
Why must a custom hook's name start with use?
- It's required for JavaScript to run it
- So React and linters know it may call hooks and apply the rules of hooks
- To make it faster
- So it is exported automatically
In useDebounce, what does the effect's cleanup do?
- Resets the value to empty
- Cancels the pending timeout when the value changes again
- Logs the value
- Nothing