A React custom hooks library a team will actually use
Which hooks belong in a shared React library, useSyncExternalStore for browser state, useEffectEvent for stale closures, and testing hooks with renderHook.
By M. Adnan Saleem · · 8 min read
On a cybersecurity platform at Primary Target, I built an internal custom hooks library and component system that standardized patterns across the frontend team, and it improved delivery velocity by approximately 30%. This is how I would build one again, with the React 19 APIs that make several of the old hand-written hooks unnecessary.
What earns a place in the library
A shared hook has a cost: everyone has to learn it, and every change to it reaches every screen. So the bar is higher than "someone wrote this twice". I would add a hook when all three hold.
- It has been written at least three times in the codebase, in slightly different ways.
- The hand-written versions have a bug in common: a missing cleanup, a stale closure, a listener added on every render, a request whose answer arrives after a newer one.
- It does one job and its name says what it returns.
Equally useful is the list of what stays out. Data fetching is the main one: a cache library such as TanStack Query already solves request deduplication, races and refetching, and a home-made useFetch solves them worse. The same goes for global state, which belongs in a store, as I argue in where React state belongs. A hook that wraps one other hook and renames it is not worth an import either.
Start with the hooks people get wrong
The first hooks in the library should be the ones whose hand-written versions are subtly broken. A debounced value is the usual first: written inline, it often forgets to clear the timer, and the result is a request for every keystroke anyway.
import { useEffect, useState } from 'react';
/** The value, once it has stopped changing for `delay` milliseconds. */
export function useDebouncedValue<T>(value: T, delay = 300): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}Small, but every copy that is replaced by this one is a copy that cannot drift.
Browser state: useSyncExternalStore
Media queries, online status, the visibility of the tab, values in localStorage: anything the browser owns is an external store, and React has had a hook for reading one since React 18. The common hand-written version, a useState plus a useEffect that subscribes, renders once with the wrong value and can tear during concurrent rendering. useSyncExternalStore does neither, and its third argument says what the server should render.
import { useCallback, useSyncExternalStore } from 'react';
/** Whether a media query matches, kept in sync with the browser. */
export function useMediaQuery(query: string, serverValue = false): boolean {
const subscribe = useCallback(
(onChange: () => void) => {
const list = window.matchMedia(query);
list.addEventListener('change', onChange);
return () => list.removeEventListener('change', onChange);
},
[query],
);
return useSyncExternalStore(
subscribe,
() => window.matchMedia(query).matches,
() => serverValue, // what the server renders, before the browser can answer
);
}subscribe is wrapped in useCallback because React re-subscribes whenever that function changes identity. Without it, the listener is removed and added again on every render.
Event handlers that see current state: useEffectEvent
The other classic bug is the stale closure: an effect that adds a listener captures the state from the render it ran in. The usual fixes were to list the state as a dependency, re-adding the listener on every change, or to keep the handler in a ref. React 19.2 made useEffectEvent stable, and it is the built-in answer: a function that always sees the latest props and state, and that does not belong in the dependency list.
import { useEffect, useEffectEvent } from 'react';
/** Listen to a window event with the latest handler, without re-subscribing on every render. */
export function useWindowEvent<K extends keyof WindowEventMap>(
type: K,
handler: (event: WindowEventMap[K]) => void,
) {
const onEvent = useEffectEvent(handler);
useEffect(() => {
const listener = (event: WindowEventMap[K]) => onEvent(event);
window.addEventListener(type, listener);
return () => window.removeEventListener(type, listener);
}, [type]);
}
// In a component: the handler reads current state, and the listener is added once
useWindowEvent('keydown', (e) => {
if (e.key === 'Escape' && open) setOpen(false);
});This is one of the hooks that lets a library shrink. A useLatest or useEventCallback written with refs can be retired once the codebase is on React 19.2.
Rules every hook follows
- The name starts with use. The
eslint-plugin-react-hooksrules only check functions named that way, and they are the cheapest reviewer the library has. - Everything it starts, it stops. Timers, listeners, subscriptions and sockets are cleaned up in the effect that created them. The real-time dashboard article has a WebSocket hook that follows the same rule.
- Return values are stable. A function a hook returns should keep its identity between renders, or every effect that depends on it re-runs.
- No hidden global state. Two components using the same hook get two independent copies, unless the hook is explicitly reading a shared store.
- SSR is decided, not discovered. If the hook touches
window, it says what the server renders.
Test hooks without a screen
renderHook from React Testing Library mounts a hook on its own, and fake timers make time-based hooks deterministic. Each hook gets a test for the behaviour people actually depend on, here that a burst of changes produces one update with the final value.
import { act, renderHook } from '@testing-library/react';
import { afterEach, expect, test, vi } from 'vitest';
import { useDebouncedValue } from './useDebouncedValue';
afterEach(() => vi.useRealTimers());
test('returns the last value once typing stops', () => {
vi.useFakeTimers();
const { result, rerender } = renderHook(({ value }) => useDebouncedValue(value, 300), {
initialProps: { value: 'a' },
});
rerender({ value: 'ab' });
rerender({ value: 'abc' });
expect(result.current).toBe('a'); // nothing yet: still typing
act(() => vi.advanceTimersByTime(300));
expect(result.current).toBe('abc'); // one update, with the final value
});Make it easy to find
A hook nobody knows about gets written again. Each one gets a short entry next to its code: what it returns, when to use it, when not to, and a two-line example. The "not for" line does more work than the rest; it stops the hook being stretched into something it was not designed to do.
## useDebouncedValue(value, delay = 300)
Returns `value` once it has stopped changing for `delay` ms.
Use it for: search boxes, filters, anything that triggers a request per keystroke.
Not for: rate-limiting clicks (disable the button instead).
const query = useDebouncedValue(input, 300);
const results = useSearch(query);Two habits keep the library healthy. In code review, a hand-written version of something the library already has gets a link to the library rather than a comment on the bug. And a hook is deprecated, with its replacement named, for a release before it is deleted.
How to tell it is working
- The copies go away. Search the codebase for
setTimeoutinside effects, ormatchMediaoutside the library. The count should fall release by release. - Review comments change. Fewer comments about cleanup and stale state, because those bugs no longer get written by hand.
- New screens start faster. A feature that used to begin by copying a hook from another screen, and fixing it, begins with an import.
Mistakes I would check for first
- A useFetch hook. Use a query cache. Requests need deduplication, cancellation and race handling, and those are solved problems.
- Hooks with options for everything. Five boolean parameters mean five hooks pretending to be one. Split them.
- useState plus useEffect for browser state. Use
useSyncExternalStore. - Refs to dodge the dependency list. On React 19.2,
useEffectEventsays what you mean. - No tests, because the hooks are small. Small and shared is exactly when a bug reaches every screen at once.
The platform this library was written for is the vehicle cybersecurity case study.
Quick answers
The short version
When should a custom hook go into a shared library?
When it has been written at least three times, the hand-written copies share a bug such as a missing cleanup or a stale closure, and it does one job. Data fetching and global state stay out: a query cache and a store already solve those.
What is useEffectEvent in React?
A hook, stable since React 19.2, that wraps a function so it always sees the latest props and state without being listed as an effect dependency. It replaces the ref-based useLatest or useEventCallback patterns for event handlers called from effects.
How do you test a custom React hook?
Mount it on its own with renderHook from React Testing Library, change its inputs with rerender, and use fake timers for anything time-based. Test the behaviour components depend on, not the implementation.
Keep reading
Related articles
- Redux Toolkit, Zustand or Context: where React state belongsServer state, shared client state, local UI state and URL state each have a natural home. When to use TanStack Query, Redux Toolkit, Zustand or Context.
- React micro frontends with Module Federation: split a monolithWhen micro frontends are worth it, how a shell and its remotes fit together, and the contracts that keep independent deploys from breaking each other.
- A real-time React dashboard that keeps up with WebSocketsWhy a live dashboard slows down over time, and the fixes: render once per frame, cap the list, aggregate as events arrive, and plan for reconnects.
The project behind this
Read the case study
What I built, where, and the numbers that came out of it.
Related experience: Frontend developer.