Custom hooks
Overview
You’ve seen the same logic appear in several components: listening for online/offline events, syncing with localStorage, debouncing an input. Custom hooks let you extract that logic into a reusable function — the main way to share behaviour between components in React.
Extracting a hook
Two components both need to know whether the browser is online:
function StatusBar() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const on = () => setIsOnline(true);
const off = () => setIsOnline(false);
window.addEventListener('online', on);
window.addEventListener('offline', off);
return () => {
window.removeEventListener('online', on);
window.removeEventListener('offline', off);
};
}, []);
return <p>{isOnline ? '✅ Online' : '❌ Disconnected'}</p>;
}
function SaveButton() {
// …the same 12 lines again…
}Move the logic into a function called useOnlineStatus:
export function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const on = () => setIsOnline(true);
const off = () => setIsOnline(false);
window.addEventListener('online', on);
window.addEventListener('offline', off);
return () => {
window.removeEventListener('online', on);
window.removeEventListener('offline', off);
};
}, []);
return isOnline;
}Now both components are short and say what they need, not how to get it:
function StatusBar() {
const isOnline = useOnlineStatus();
return <p>{isOnline ? '✅ Online' : '❌ Disconnected'}</p>;
}
function SaveButton() {
const isOnline = useOnlineStatus();
return <button disabled={!isOnline}>{isOnline ? 'Save' : 'Reconnecting…'}</button>;
}Hooks share logic, not state
Each call to a custom hook is completely independent. StatusBar and SaveButton each have their own isOnline state and their own event listeners — the hook is like copying and pasting its body into each component. (Here both happen to show the same value because they listen to the same browser events.)
If you need components to share the same state, lift it up or use context — a hook alone won’t do it.
Naming rules
- Must start with
usefollowed by a capital letter:useOnlineStatus,useCourse,useDebouncedValue. React and the linter rely on this to apply the Rules of Hooks. - Only functions that call hooks should start with
use. A plain helper likeformatPrice()shouldn’t be nameduseFormatPrice(). - Name hooks after their purpose, not after when they run.
useChatRoom(roomId)anduseWindowWidth()are good;useMount(fn)oruseEffectOnce(fn)hide what’s really happening and tend to cause bugs.
Passing values into hooks
Hooks take arguments like any function, and because they run on every render, they always receive the latest values:
export function useChatRoom({ serverUrl, roomId }) {
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => connection.disconnect();
}, [serverUrl, roomId]);
}
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://chat.example');
useChatRoom({ serverUrl, roomId });
// …
}When roomId changes, ChatRoom re-renders, calls useChatRoom with the new value, and the effect inside reconnects. Hooks are reactive in the same way components are.
More useful hooks
useLocalStorage
export function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
// const [theme, setTheme] = useLocalStorage('theme', 'light');useDebouncedValue
export function useDebouncedValue(value, delay = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}
// const debouncedQuery = useDebouncedValue(query, 300);
// fetch results for debouncedQuery instead of every keystrokeuseMediaQuery
export function useMediaQuery(query) {
const [matches, setMatches] = useState(() => window.matchMedia(query).matches);
useEffect(() => {
const mql = window.matchMedia(query);
const onChange = () => setMatches(mql.matches);
mql.addEventListener('change', onChange);
onChange();
return () => mql.removeEventListener('change', onChange);
}, [query]);
return matches;
}
// const isMobile = useMediaQuery('(max-width: 640px)');For subscriptions to external stores like these, React also provides
useSyncExternalStore, which avoids some edge cases during concurrent rendering — see External stores.
What to put in a custom hook
Good candidates:
- an effect plus the state it manages (subscriptions, timers, browser APIs),
- a piece of logic repeated across components,
- a complex piece of a component that’s easier to understand with a name.
Not every repeated useState needs a hook. Extract when the hook gives the logic a clear name and a simpler interface than the code it hides.
Testing custom hooks
Test a hook through a small component that uses it, or with Testing Library’s renderHook:
import { renderHook, act } from '@testing-library/react';
test('useLocalStorage persists the value', () => {
const { result } = renderHook(() => useLocalStorage('k', 1));
act(() => result.current[1](2));
expect(JSON.parse(localStorage.getItem('k'))).toBe(2);
});Hooks you don’t have to write
Before writing a hook, check whether a library already does it well: TanStack Query for server data, React Router hooks for URLs, React Hook Form for forms, and collections like usehooks-ts. Writing your own is still great practice — and the patterns in this lesson are exactly what those libraries do internally.
Smell test: if a component has an effect in it, ask whether it would read better as
const x = useSomething(…). Wrapping effects in well-named hooks is one of the best ways to keep components declarative.
useLocalStorage and useDebouncedValue
Write useLocalStorage(key, initialValue) that works like useState but reads the initial value from localStorage (parsing JSON, falling back to initialValue if missing or invalid) and writes the value back whenever it changes. Then write useDebouncedValue(value, delay) that returns value only after it has stopped changing for delay ms. Use both in a CourseSearch that remembers the last query and only filters when typing pauses for 300 ms.
import { useEffect, useState } from 'react';
export function useLocalStorage(key, initialValue) {
// your code here
}
export function useDebouncedValue(value, delay) {
// your code here
}import { useEffect, useState } from 'react';
export function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
export function useDebouncedValue(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}
export function CourseSearch({ courses }) {
const [query, setQuery] = useLocalStorage('course-query', '');
const debouncedQuery = useDebouncedValue(query, 300);
const results = courses.filter((c) =>
c.title.toLowerCase().includes(debouncedQuery.toLowerCase())
);
return (
<>
<input aria-label="Search" value={query} onChange={(e) => setQuery(e.target.value)} />
<ul>
{results.map((c) => <li key={c.id}>{c.title}</li>)}
</ul>
</>
);
}Summary
- A custom hook is a function whose name starts with
useand which calls other hooks. - Custom hooks share stateful logic, not state — every component that calls one gets its own state.
- They follow the Rules of Hooks and re-run on every render of the component using them.
- Name hooks after what they do (
useOnlineStatus,useCourse), not after lifecycle (useMount). - Good hooks hide an effect or a subscription behind a simple, declarative API.