Custom hooks

Topic 5 of 5 in Refs & effects7 min readIntermediateFree course

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:

JSX
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:

JSX
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:

JSX
function StatusBar() {
  const isOnline = useOnlineStatus();
  return <p>{isOnline ? '✅ Online' : '❌ Disconnected'}</p>;
}

function SaveButton() {
  const isOnline = useOnlineStatus();
  return <button disabled={!isOnline}>{isOnline ? 'Save' : 'Reconnecting…'}</button>;
}

useOnlineStatus contains a useState and a useEffect that subscribes to online events, and returns online. StatusBar and SaveButton both call useOnlineStatus(), and each gets its own independent state.

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 use followed 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 like formatPrice() shouldn’t be named useFormatPrice().
  • Name hooks after their purpose, not after when they run. useChatRoom(roomId) and useWindowWidth() are good; useMount(fn) or useEffectOnce(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:

JSX
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

JSX
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

JSX
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 keystroke

useMediaQuery

JSX
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:

JSX
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.

Exercise

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.

JavaScript
import { useEffect, useState } from 'react';

export function useLocalStorage(key, initialValue) {
  // your code here
}

export function useDebouncedValue(value, delay) {
  // your code here
}

Summary

  • A custom hook is a function whose name starts with use and 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.