Tech Interview RoomStudy guides

React

What are custom hooks? Write one and explain the Rules of Hooks.

Intermediate · 2 min read · Lesson 7 of 14 in React

A custom hook is a function whose name starts with use and that calls other hooks. It extracts stateful logic so components can reuse it. Each component calling the hook gets its own state; hooks share logic, not state.

Rules of Hooks

  1. Call hooks only at the top level of a component or custom hook: never in conditions, loops, nested functions or after an early return.
  2. Call them only from React function components or custom hooks.

Why: React identifies each hook by its call order in the component. If a condition skips one hook, every later hook reads the wrong slot. The eslint-plugin-react-hooks rules enforce this. (The new use() API is the exception: it can be called conditionally.)

Good custom hooks

Have a clear name and contract (useDebouncedValue, useLocalStorage, useOnlineStatus, useMediaQuery), clean up after themselves, and return stable values when possible.

Example

jsx
function useDebouncedValue(value, delay = 300) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(id);
  }, [value, delay]);
  return debounced;
}

function useLocalStorage(key, initial) {
  const [value, setValue] = useState(() => {
    try {
      const stored = localStorage.getItem(key);
      return stored !== null ? JSON.parse(stored) : initial;
    } catch {
      return initial;
    }
  });
  useEffect(() => {
    try { localStorage.setItem(key, JSON.stringify(value)); } catch {}
  }, [key, value]);
  return [value, setValue];
}

function SearchBox() {
  const [query, setQuery] = useState('');
  const debounced = useDebouncedValue(query, 400);
  const { data } = useQuery({ queryKey: ['search', debounced], queryFn: () => search(debounced), enabled: debounced.length > 1 });
  return <input value={query} onChange={e => setQuery(e.target.value)} />;
}

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you test a custom hook?

With React Testing Library's renderHook: const { result } = renderHook(() => useCounter()), then act(() => result.current.increment()) and assert on result.current. Use fake timers (vi.useFakeTimers()) for debounce hooks. Often the best test is a small component that uses the hook, tested through the UI.