Lesson 5 of 8
Testing Hooks with renderHook
renderHook tests custom hooks in isolation - without building a component just to test the hook's behavior. It provides `result` (the hook's return value) and `rerender` (to trigger updates). Combined with `act()` for async updates, it covers all hook testing scenarios.
renderHook - Testing Custom Hooks
import { renderHook, act } from '@testing-library/react';
import { useCounter } from './useCounter';
import { useAsync } from './useAsync';
import { useLocalStorage } from './useLocalStorage';
// ---- Testing useCounter ----
describe('useCounter', () => {
it('starts at initial value', () => {
const { result } = renderHook(() => useCounter(10));
expect(result.current.count).toBe(10);
});
it('increments', () => {
const { result } = renderHook(() => useCounter(0));
act(() => result.current.increment());
expect(result.current.count).toBe(1);
});
it('resets to initial value', () => {
const { result } = renderHook(() => useCounter(5));
act(() => result.current.increment());
act(() => result.current.reset());
expect(result.current.count).toBe(5);
});
it('respects max value', () => {
const { result } = renderHook(() => useCounter(0, { max: 3 }));
act(() => { result.current.increment(); result.current.increment(); result.current.increment(); result.current.increment(); });
expect(result.current.count).toBe(3); // capped at max
});
});
// ---- Testing async hook ----
describe('useAsync', () => {
it('starts idle', () => {
const { result } = renderHook(() => useAsync(vi.fn()));
expect(result.current.status).toBe('idle');
expect(result.current.data).toBeNull();
});
it('sets loading then success', async () => {
const mockFn = vi.fn().mockResolvedValue({ name: 'Alice' });
const { result } = renderHook(() => useAsync(mockFn));
expect(result.current.isIdle).toBe(true);
await act(async () => { await result.current.execute(); });
expect(result.current.isSuccess).toBe(true);
expect(result.current.data).toEqual({ name: 'Alice' });
});
it('sets error state on rejection', async () => {
const mockFn = vi.fn().mockRejectedValue(new Error('Network failure'));
const { result } = renderHook(() => useAsync(mockFn));
await act(async () => { await result.current.execute(); });
expect(result.current.isError).toBe(true);
expect(result.current.error?.message).toBe('Network failure');
});
});
// ---- Testing hook with re-renders ----
describe('useLocalStorage', () => {
beforeEach(() => localStorage.clear());
it('reads from localStorage', () => {
localStorage.setItem('user', JSON.stringify({ name: 'Bob' }));
const { result } = renderHook(() => useLocalStorage('user', null));
expect(result.current[0]).toEqual({ name: 'Bob' });
});
it('updates localStorage on value change', () => {
const { result } = renderHook(() => useLocalStorage('theme', 'light'));
act(() => result.current[1]('dark'));
expect(localStorage.getItem('theme')).toBe('"dark"');
});
it('survives re-renders', () => {
const { result, rerender } = renderHook(() => useLocalStorage('count', 0));
act(() => result.current[1](42));
rerender(); // simulate parent re-render
expect(result.current[0]).toBe(42);
});
});Tip
Tip
Practice Testing Hooks with renderHook in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Testing Hooks with renderHook
Practice Task
Note
Practice Task - (1) Write a working example of Testing Hooks with renderHook from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Testing Hooks with renderHook is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?