Course contentsShow
← React
Lesson 996 of 2,39625. Custom HooksFree lesson

Testing Composed Custom Hooks

Use renderHook from React Testing Library to test custom hooks that compose multiple other hooks together.

Testing Composed Custom Hooks

You'll learn how to use renderHook from React Testing Library to test custom hooks that compose multiple other hooks together.

Why Test Composed Hooks?

When you build a custom hook that combines several other hooks (like a useLocalStorage that uses both useState and useEffect), you need a way to test it outside a real component. You can't just call the hook directly in a test — remember, hooks must follow the Rules of Hooks. That's where renderHook comes in.

The renderHook Utility

renderHook creates a minimal "test harness" component that calls your hook for you. It returns a result object containing your hook's return value:

import { renderHook } from '@testing-library/react';
import { useToggle } from './useToggle';

test('useToggle starts false and toggles', () => {
  const { result } = renderHook(() => useToggle(false));
  
  expect(result.current).toBe(false);
  
  // Act on the toggle function (second element in array)
  // We'll cover interaction patterns in future lessons
});

Testing Composed Hooks

For hooks that compose multiple others, the test structure is identical. Whether your hook uses one built-in hook or five, renderHook handles it:

test('useLocalStorage reads and updates', () => {
  const { result } = renderHook(() => useLocalStorage('key', 'default'));
  
  // result.current contains whatever your hook returns
  expect(result.current[0]).toBe('default');
});

The result.current property always reflects the current return value of your hook, just as if a real component had called it.

Key Takeaway: Use renderHook from React Testing Library to test any custom hook (simple or composed) by wrapping the hook call in a test harness, then asserting against result.current.