CodePark/ questions / Hooks, context & providers
START PRACTICINGPRACTICE
Frontend question · Testing › Hooks, context & providers

How do you test a custom hook? When would you test it through a component instead?

import { renderHook, act } from "@testing-library/react";

test("increments", () => {
  const { result } = renderHook(() => useCounter(5));
  act(() => result.current.increment());
  expect(result.current.count).toBe(6);
});

Use renderHook from @testing-library/react. The separate @testing-library/react-hooks package is deprecated.

How it works:

  • It renders a tiny test component that calls your hook.
  • It returns result. result.current is the hook's latest return value.
  • Call state-changing functions inside act, then read result.current again.
  • Use rerender(newProps) to test how the hook reacts to new arguments.
  • Use the wrapper option to supply providers.

renderHook fits reusable hooks with real logic, like useDebounce, usePagination or a hook in a shared library.

If only one component uses a hook, testing that component is usually better. It covers the hook through real behaviour. And your tests don't depend on how the code is split internally.

  • Use renderHook from @testing-library/react.
  • result.current holds the hook's latest return value.
  • Wrap updates in act, and use rerender for new props.
  • Use the wrapper option to supply providers.
  • Test through a component when the hook is an internal detail of it.