| How to Mock API Requests in React Tests :👈 | 👉:How to Test Loading and Error States |
How to Test Custom Hooks |
How to Test Custom Hooks in React
1. What Are Custom Hooks?
Custom hooks are JavaScript functions that allow us to reuse React logic across multiple components.
They usually start with the word use, such as:
- useCounter()
- useFetch()
- useAuth()
- useLocalStorage()
- useDebounce()
Example of a simple custom hook:
import { useState } from 'react';
function useCounter() {
const [count, setCount] = useState(0);
function increment() {
setCount(prev => prev + 1);
}
function decrement() {
setCount(prev => prev - 1);
}
return {
count,
increment,
decrement
};
}
export default useCounter;
Instead of repeating counter logic in multiple components, we can reuse this hook wherever required.
2. Why Should We Test Custom Hooks?
- Verify that state updates work correctly.
- Ensure reusable logic behaves as expected.
- Test asynchronous operations.
- Verify API success and failure scenarios.
- Check useEffect behavior and cleanup.
- Identify bugs before integrating hooks into components.
- Ensure future changes do not break existing functionality.
3. Tools Required
| Tool | Purpose |
|---|---|
| React Testing Library | Provides renderHook() to execute custom hooks in a React testing environment. |
| Vitest | Runs tests and provides assertions and mocking. |
| React | Provides hooks such as useState and useEffect. |
| jsdom | Provides a browser-like DOM environment. |
Install packages
npm install -D vitest jsdom
npm install -D @testing-library/react
npm install -D @testing-library/jest-dom
Configure Vitest
vite.config.js
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: './src/test/setup.js'
}
});
src/test/setup.js
import '@testing-library/jest-dom/vitest';
4. Understanding renderHook()
renderHook() is a utility provided by React Testing Library to execute a custom hook within a React test environment.
Normally, React hooks cannot be called directly inside ordinary JavaScript functions or test cases. They must be called from React components or other custom hooks.
renderHook() provides the React environment needed to test them.
Example:
import { renderHook } from '@testing-library/react';
const { result } = renderHook(() => useCounter());
console.log(result.current.count);
Important properties:
renderHook()– Renders the custom hook in a test component.result.current– Provides the latest value returned by the hook.rerender()– Renders the hook again, optionally with new props.unmount()– Unmounts the test component and runs effect cleanup.
5. Test a Simple Counter Hook
Let's test the useCounter() hook created earlier.
useCounter.test.js
import { renderHook, act } from '@testing-library/react';
import { describe, it, expect } from 'vitest';
import useCounter from './useCounter';
describe('useCounter', () => {
it('initializes counter with zero', () => {
const { result } = renderHook(() => useCounter());
expect(result.current.count).toBe(0);
});
it('increments counter', () => {
const { result } = renderHook(() => useCounter());
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
});
it('decrements counter', () => {
const { result } = renderHook(() => useCounter());
act(() => {
result.current.decrement();
});
expect(result.current.count).toBe(-1);
});
});
What is act()?
act() ensures that React processes updates caused by an interaction before we check the result.
For example:
act(() => {
result.current.increment();
});
This executes the state update and allows React to complete the resulting rendering work.
Remember: Use act() when directly calling hook functions that trigger React updates. React Testing Library's user interaction utilities already handle act() for their own interactions.
6. Test a Hook That Accepts Parameters
Custom hooks can accept parameters to make their behavior configurable.
Example: useCounter(initialValue)
import { useState } from 'react';
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
function increment() {
setCount(prev => prev + 1);
}
return {
count,
increment
};
}
export default useCounter;
Test:
it('initializes counter with provided value', () => {
const { result } = renderHook(
() => useCounter(10)
);
expect(result.current.count).toBe(10);
});
This verifies that the hook uses the initial value provided by the caller.
7. Test Hook Updates Using rerender()
Sometimes a custom hook receives props or parameters that can change during its lifecycle.
Example: useDouble()
import { useMemo } from 'react';
function useDouble(number) {
return useMemo(() => number * 2, [number]);
}
export default useDouble;
Test:
it('updates result when input changes', () => {
const { result, rerender } = renderHook(
({ value }) => useDouble(value),
{
initialProps: { value: 5 }
}
);
expect(result.current).toBe(10);
rerender({ value: 10 });
expect(result.current).toBe(20);
});
Explanation:
- initialProps provides the initial hook input.
- rerender() runs the hook again with updated props.
- result.current gives the latest returned value.
8. Test Custom Hooks That Use useEffect()
Many custom hooks use useEffect() to perform operations when a component is mounted or when dependencies change.
Example: useDocumentTitle()
import { useEffect } from 'react';
function useDocumentTitle(title) {
useEffect(() => {
document.title = title;
}, [title]);
}
export default useDocumentTitle;
Test:
import { renderHook } from '@testing-library/react';
it('updates document title', () => {
renderHook(() => useDocumentTitle('Dashboard'));
expect(document.title).toBe('Dashboard');
});
Test dependency changes
it('updates document title when title changes', () => {
const { rerender } = renderHook(
({ title }) => useDocumentTitle(title),
{
initialProps: { title: 'Home' }
}
);
expect(document.title).toBe('Home');
rerender({ title: 'Dashboard' });
expect(document.title).toBe('Dashboard');
});
9. Test API Calls Inside Custom Hooks
Let's create a custom hook that fetches user information from an API.
useUsers.js
import { useEffect, useState } from 'react';
function useUsers() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
async function fetchUsers() {
try {
const response = await fetch(
'https://api.example.com/users'
);
if (!response.ok) {
throw new Error('Failed to fetch users');
}
const data = await response.json();
setUsers(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchUsers();
}, []);
return {
users,
loading,
error
};
}
export default useUsers;
Test successful API response
import { renderHook, waitFor } from '@testing-library/react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import useUsers from './useUsers';
describe('useUsers', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('fetches and returns users', async () => {
const mockUsers = [
{ id: 1, name: 'John' },
{ id: 2, name: 'David' }
];
vi.spyOn(globalThis, 'fetch')
.mockResolvedValue({
ok: true,
json: async () => mockUsers
});
const { result } = renderHook(() => useUsers());
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
expect(result.current.users).toEqual(mockUsers);
expect(result.current.error).toBe('');
});
});
Test API failure
it('handles API errors', async () => {
vi.spyOn(globalThis, 'fetch')
.mockResolvedValue({
ok: false,
status: 500
});
const { result } = renderHook(() => useUsers());
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
expect(result.current.error)
.toBe('Failed to fetch users');
expect(result.current.users).toEqual([]);
});
Test initial loading state
it('starts with loading state', () => {
vi.spyOn(globalThis, 'fetch')
.mockReturnValue(new Promise(() => {}));
const { result } = renderHook(() => useUsers());
expect(result.current.loading).toBe(true);
expect(result.current.users).toEqual([]);
});
Here, the Promise intentionally remains pending so that we can verify the initial loading state.
10. Test Cleanup in Custom Hooks
Some hooks register event listeners, subscriptions, or timers. These should be cleaned up when the component using the hook is unmounted.
Example: useWindowWidth()
import { useEffect, useState } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return width;
}
export default useWindowWidth;
Test event listener cleanup
it('removes resize listener on unmount', () => {
const removeSpy = vi.spyOn(
window,
'removeEventListener'
);
const { unmount } = renderHook(() => useWindowWidth());
unmount();
expect(removeSpy).toHaveBeenCalledWith(
'resize',
expect.any(Function)
);
removeSpy.mockRestore();
});
This test verifies that the hook removes the resize listener when it is unmounted.
11. Test Custom Hooks Using a Wrapper
Some hooks depend on React Context providers such as authentication, theme, or application settings.
For these hooks, we can provide a wrapper component to supply the required context.
Example:
import { createContext, useContext } from 'react';
export const AuthContext = createContext(null);
export function useAuth() {
return useContext(AuthContext);
}
Test:
import { renderHook } from '@testing-library/react';
import { AuthContext, useAuth } from './AuthContext';
it('reads authentication context', () => {
const mockUser = {
id: 1,
name: 'John'
};
const wrapper = ({ children }) => (
<AuthContext.Provider value={mockUser}>
{children}
</AuthContext.Provider>
);
const { result } = renderHook(
() => useAuth(),
{ wrapper }
);
expect(result.current).toEqual(mockUser);
});
Why use wrapper?
It provides the same context environment that the hook would receive when used inside the real application.
12. Test a Debounce Custom Hook
A debounce hook delays updating a value until a specified amount of time has passed without another change.
It is commonly used in search boxes to avoid making API requests for every keystroke.
useDebounce.js
import { useEffect, useState } from 'react';
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
export default useDebounce;
Test using Vitest fake timers:
import { renderHook, act } from '@testing-library/react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import useDebounce from './useDebounce';
describe('useDebounce', () => {
afterEach(() => {
vi.useRealTimers();
});
it('updates value after specified delay', () => {
vi.useFakeTimers();
const { result, rerender } = renderHook(
({ value }) => useDebounce(value, 500),
{
initialProps: { value: 'React' }
}
);
expect(result.current).toBe('React');
rerender({ value: 'React Testing' });
expect(result.current).toBe('React');
act(() => {
vi.advanceTimersByTime(500);
});
expect(result.current).toBe('React Testing');
});
});
This test verifies that the value changes only after the specified delay.
13. renderHook() vs Rendering a Component
| renderHook() | render() |
|---|---|
| Used to test custom hooks directly. | Used to test React components. |
| Provides result.current to access hook output. | Provides screen queries to inspect rendered UI. |
| Useful for isolated reusable logic. | Useful for testing user-visible behavior. |
| Can use rerender() to change hook props. | Can rerender components with new props. |
Important: Do not test every hook in isolation. If the hook is tightly connected to a component's behavior, testing the component through its visible UI may provide more meaningful coverage.
14. Best Practices
- Test the hook's returned values and observable behavior.
- Use renderHook() for isolated custom hook tests.
- Use act() for direct state-changing hook operations.
- Use waitFor() for asynchronous state changes.
- Test initial state, updated state, and error conditions.
- Test useEffect cleanup when the hook registers listeners or subscriptions.
- Use wrappers for hooks that depend on Context providers.
- Use fake timers for debounce and timeout hooks.
- Restore mocks and timers after each test.
- Avoid testing React's internal implementation details.
- Keep tests focused on one behavior at a time.
15. Common Mistakes
| Mistake | Correct approach |
|---|---|
| Calling a hook directly inside a test. | Use renderHook(). |
| Checking state immediately after an update. | Use act() for direct updates. |
| Not waiting for asynchronous operations. | Use waitFor() or findBy... where appropriate. |
| Ignoring effect cleanup. | Test unmount behavior. |
| Forgetting Context dependencies. | Provide a wrapper with the required provider. |
| Not restoring fake timers. | Use vi.useRealTimers() after tests. |
| Testing internal implementation details. | Test returned values and observable behavior. |
16. Interview Questions and Answers
1. How do you test custom hooks in React?
We use React Testing Library's renderHook() utility to execute custom hooks and inspect their returned values and behavior.
2. What is renderHook()?
It is a testing utility that renders a hook inside a React test environment without requiring us to create a separate test component manually.
3. What is result.current?
It contains the latest value returned by the custom hook.
4. What is the purpose of act()?
It ensures React processes state updates and related rendering work before assertions are performed.
5. What is rerender()?
It reruns the hook with updated props, allowing us to test how the hook responds to changing inputs.
6. How do you test API calls inside custom hooks?
Mock the API function or fetch request, render the hook, wait for asynchronous updates, and verify the returned data, loading state, or error state.
7. How do you test useEffect cleanup?
Render the hook, unmount it using unmount(), and verify that event listeners, subscriptions, or other resources are cleaned up.
8. How do you test hooks that use Context?
Pass a wrapper component to renderHook() that provides the required Context provider and value.
9. Can we test custom hooks without components?
Yes. renderHook() creates the necessary React test environment, so a separate application component is not required.
10. When should we test a hook through a component instead?
When the main requirement is to verify how the hook affects user-visible behavior, testing the component can provide a more realistic test.
17. Summary
Testing custom hooks helps ensure that reusable React logic works correctly and remains reliable as the application grows.
Important methods to remember:
- renderHook() – Executes a custom hook in a React test environment.
- result.current – Reads the latest hook output.
- act() – Processes React state updates before assertions.
- rerender() – Tests changes in hook inputs.
- waitFor() – Waits for asynchronous conditions.
- unmount() – Tests effect cleanup.
- wrapper – Provides Context or other required providers.
Key takeaway: Use renderHook() to test reusable hook logic, but also test important user-facing behavior through the components that use those hooks.
| How to Mock API Requests in React Tests :👈 | 👉:How to Test Loading and Error States |
Comments and Discussion