| Why Should Not Call Hooks Conditionally :👈 | 👉:Identify Unnecessary React Re-renders |
How to Test Custom React Hooks |
How to Test Custom React Hooks in React
1. What Is a Custom React Hook?
A custom Hook is a JavaScript function that uses React Hooks to encapsulate and reuse stateful logic between components.
Custom Hooks usually begin with the word use, followed by a descriptive name.
For example, consider a custom Hook that manages a counter.
import { useState } from "react";
export function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => {
setCount(previousCount => previousCount + 1);
};
const decrement = () => {
setCount(previousCount => previousCount - 1);
};
const reset = () => {
setCount(initialValue);
};
return {
count,
increment,
decrement,
reset
};
}
This Hook manages a counter and exposes its current value and three operations.
Testing this Hook helps verify that:
- The initial count is correct.
- Incrementing increases the count.
- Decrementing decreases the count.
- Resetting restores the initial value.
2. Why Should You Test Custom Hooks?
Testing custom Hooks helps you verify reusable logic independently of the components that use it.
Common reasons to test custom Hooks include:
- Correctness: Verify that state updates and calculations work as expected.
- Regression prevention: Detect when a future change breaks existing behavior.
- Asynchronous behavior: Verify loading, success, and error states.
- Cleanup: Ensure timers, subscriptions, and event listeners are cleaned up correctly.
- Reusability: Confirm that the Hook works correctly when used by different components.
3. Recommended Testing Tools
For modern React applications, a common testing setup includes the following tools.
- React Testing Library: Provides utilities for testing React components and custom Hooks.
renderHook: Renders a custom Hook in a test environment and exposes its returned values.- Vitest: A test runner that supports assertions, mocks, and spies.
- Jest: An alternative test runner with its own mocking and assertion utilities.
act: Ensures React updates triggered by test operations are processed before assertions.
Older tutorials may recommend the standalone @testing-library/react-hooks package. For modern React projects, use renderHook from @testing-library/react unless you have a specific reason to maintain an older setup.
4. Set Up the Testing Environment
The following example uses React, Vitest, React Testing Library, and a DOM environment provided by JSDOM.
Step 1: Install the Dependencies
For an existing React project, install the required development dependencies:
npm install -D vitest @testing-library/react @testing-library/jest-dom jsdom
React and React DOM should already be installed in your React application.
Step 2: Configure Vitest
If you use Vite, configure the test environment in vite.config.js.
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
setupFiles: "./src/test/setup.js",
restoreMocks: true
}
});
Make sure @vitejs/plugin-react is installed if your project uses this configuration.
Step 3: Create the Test Setup File
Create src/test/setup.js:
import "@testing-library/jest-dom/vitest";
This enables additional DOM assertions when testing React components. The basic Hook tests below do not depend on these matchers, but they can be useful when testing components.
Step 4: Add a Test Script
In package.json, add a script under scripts:
{
"scripts": {
"test": "vitest",
"test:run": "vitest run"
}
}
Merge these entries with your existing scripts rather than replacing the entire section.
5. Test a Simple Custom Hook with renderHook
The renderHook utility lets you test a Hook without creating a separate test component yourself.
Suppose the Hook is stored in src/hooks/useCounter.js.
Hook implementation:
import { useState } from "react";
export function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => {
setCount(previousCount => previousCount + 1);
};
const decrement = () => {
setCount(previousCount => previousCount - 1);
};
const reset = () => {
setCount(initialValue);
};
return {
count,
increment,
decrement,
reset
};
}
Test implementation:
import { renderHook, act } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { useCounter } from "./useCounter";
describe("useCounter", () => {
it("initializes the counter to zero", () => {
const { result } = renderHook(() => useCounter());
expect(result.current.count).toBe(0);
});
it("increments the counter", () => {
const { result } = renderHook(() => useCounter());
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
});
it("decrements the counter", () => {
const { result } = renderHook(() => useCounter());
act(() => {
result.current.decrement();
});
expect(result.current.count).toBe(-1);
});
it("resets to the initial value", () => {
const { result } = renderHook(() => useCounter(10));
act(() => {
result.current.increment();
});
act(() => {
result.current.reset();
});
expect(result.current.count).toBe(10);
});
});
How Does This Test Work?
renderHookrenders a component that executes the custom Hook.result.currentexposes the Hook's latest returned value.actwraps operations that trigger React updates.expectverifies that the returned state matches the expected result.
Important: When the Hook updates state, read its latest output through result.current after the update has been processed. Do not expect an old object reference to update automatically.
6. Test Hooks That Accept Parameters
Custom Hooks often accept parameters that affect their behavior. Test both default values and custom values.
Consider this Hook:
import { useState } from "react";
export function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = () => {
setValue(previousValue => !previousValue);
};
return { value, toggle };
}
Test its default and custom initial values:
import { renderHook, act } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { useToggle } from "./useToggle";
describe("useToggle", () => {
it("uses false by default", () => {
const { result } = renderHook(() => useToggle());
expect(result.current.value).toBe(false);
});
it("supports a custom initial value", () => {
const { result } = renderHook(() => useToggle(true));
expect(result.current.value).toBe(true);
});
it("toggles the value", () => {
const { result } = renderHook(() => useToggle());
act(() => {
result.current.toggle();
});
expect(result.current.value).toBe(true);
act(() => {
result.current.toggle();
});
expect(result.current.value).toBe(false);
});
});
These tests verify the Hook's public behavior rather than its internal implementation details.
7. Test Hooks When Props Change with rerender
Some Hooks depend on values passed as arguments. React Testing Library provides rerender to render the Hook again with new arguments.
Consider a Hook that calculates a price with a tax rate:
import { useMemo } from "react";
export function usePriceWithTax(price, taxRate) {
return useMemo(() => {
return price + price * taxRate;
}, [price, taxRate]);
}
Test it with different inputs:
import { renderHook } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { usePriceWithTax } from "./usePriceWithTax";
describe("usePriceWithTax", () => {
it("calculates the price with tax", () => {
const { result } = renderHook(
({ price, taxRate }) => usePriceWithTax(price, taxRate),
{
initialProps: {
price: 100,
taxRate: 0.1
}
}
);
expect(result.current).toBeCloseTo(110);
});
it("recalculates when the inputs change", () => {
const { result, rerender } = renderHook(
({ price, taxRate }) => usePriceWithTax(price, taxRate),
{
initialProps: {
price: 100,
taxRate: 0.1
}
}
);
rerender({
price: 200,
taxRate: 0.2
});
expect(result.current).toBeCloseTo(240);
});
});
Here, rerender passes updated props to the Hook. The result should reflect the new values.
Note: This test verifies the calculation's behavior. It does not prove that useMemo avoided a recalculation. Tests should generally focus on observable behavior rather than React's internal memoization decisions.
8. Test Asynchronous Custom Hooks
Hooks that fetch data or perform asynchronous operations need tests for loading, success, and error states.
Consider a Hook that loads a user from an API.
Custom Hook: useUser
import { useEffect, useState } from "react";
export function useUser(userId) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(Boolean(userId));
const [error, setError] = useState(null);
useEffect(() => {
if (!userId) {
setUser(null);
setLoading(false);
setError(null);
return;
}
const controller = new AbortController();
async function loadUser() {
setLoading(true);
setError(null);
try {
const response = await fetch(
`/api/users/${userId}`,
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Failed to load user");
}
const data = await response.json();
setUser(data);
} catch (err) {
if (err.name !== "AbortError") {
setError(err);
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
loadUser();
return () => {
controller.abort();
};
}, [userId]);
return { user, loading, error };
}
This Hook:
- Starts loading when a user ID is provided.
- Fetches the user data.
- Stores the returned user.
- Exposes loading and error states.
- Aborts the request when the Effect is cleaned up.
When userId changes, the previous Effect is cleaned up and its request is aborted before the new Effect synchronizes with the new ID.
9. Mock API Calls in Tests
You should generally avoid depending on a real backend when unit testing a custom Hook. Mock the network response so tests remain predictable and can run without a live API.
The following example uses Vitest's vi.stubGlobal to replace fetch.
import { renderHook, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, afterEach } from "vitest";
import { useUser } from "./useUser";
describe("useUser", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("loads a user successfully", async () => {
const mockUser = {
id: 1,
name: "Sam"
};
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
ok: true,
json: vi.fn().mockResolvedValue(mockUser)
})
);
const { result } = renderHook(() => useUser("1"));
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
expect(result.current.user).toEqual(mockUser);
expect(result.current.error).toBe(null);
expect(fetch).toHaveBeenCalledWith(
"/api/users/1",
expect.objectContaining({
signal: expect.any(AbortSignal)
})
);
});
});
What Does waitFor Do?
waitFor repeatedly evaluates its callback until the assertion succeeds or the timeout is reached.
It is useful when a test needs to wait for a state change caused by an asynchronous operation.
Do not use an arbitrary fixed delay such as setTimeout(..., 1000) just to give an API request time to finish. Wait for the expected observable state instead.
10. Test API Error Handling
A reliable data-fetching Hook should handle failed requests.
For example, the server might return an unsuccessful HTTP response.
import { renderHook, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, afterEach } from "vitest";
import { useUser } from "./useUser";
describe("useUser error handling", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("exposes an error when the API request fails", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
ok: false,
status: 500,
json: vi.fn()
})
);
const { result } = renderHook(() => useUser("1"));
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
expect(result.current.user).toBe(null);
expect(result.current.error).toBeInstanceOf(Error);
expect(result.current.error.message).toBe(
"Failed to load user"
);
});
});
This test verifies that the Hook exposes an error rather than treating an unsuccessful HTTP response as a successful request.
11. Test Hook Cleanup
Some Hooks create resources that must be released when the component unmounts, including:
- Timers and intervals.
- Event listeners.
- WebSocket connections.
- Subscriptions.
- Network requests that can be aborted.
Consider a Hook that creates an interval:
import { useEffect } from "react";
export function useInterval(callback, delay) {
useEffect(() => {
if (delay == null) {
return;
}
const timerId = setInterval(callback, delay);
return () => {
clearInterval(timerId);
};
}, [callback, delay]);
}
Because callback is a dependency, a new callback reference causes the interval to be cleaned up and recreated. If callers pass a new inline function on every render, this can happen frequently.
Test that the interval is removed when the Hook unmounts:
import { renderHook } from "@testing-library/react";
import { describe, it, expect, vi, afterEach } from "vitest";
import { useInterval } from "./useInterval";
describe("useInterval", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("clears the interval when unmounted", () => {
const clearIntervalSpy = vi.spyOn(
globalThis,
"clearInterval"
);
const callback = vi.fn();
const { unmount } = renderHook(
() => useInterval(callback, 1000)
);
unmount();
expect(clearIntervalSpy).toHaveBeenCalled();
});
});
This test verifies that cleanup occurs. It does not verify how often the callback executes. Use fake timers for tests that need to check interval timing.
12. Test Timers with Fake Timers
For timer-based Hooks, fake timers let you advance time without waiting for real seconds to pass.
For example, suppose a Hook increments a value every second:
import { useEffect, useState } from "react";
export function useTimer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const timerId = setInterval(() => {
setSeconds(previous => previous + 1);
}, 1000);
return () => {
clearInterval(timerId);
};
}, []);
return seconds;
}
Test it using Vitest fake timers:
import { renderHook, act } from "@testing-library/react";
import { describe, it, expect, vi, afterEach } from "vitest";
import { useTimer } from "./useTimer";
describe("useTimer", () => {
afterEach(() => {
vi.useRealTimers();
});
it("increments once per second", () => {
vi.useFakeTimers();
const { result, unmount } = renderHook(() => useTimer());
expect(result.current).toBe(0);
act(() => {
vi.advanceTimersByTime(1000);
});
expect(result.current).toBe(1);
act(() => {
vi.advanceTimersByTime(2000);
});
expect(result.current).toBe(3);
unmount();
});
});
Here, vi.advanceTimersByTime advances the fake clock. Wrapping it in act ensures React processes the state updates before the assertions.
13. Should You Test a Custom Hook Directly or Through a Component?
Both approaches are useful, depending on the purpose of the test.
| Testing Approach | Best For | Advantages |
|---|---|---|
renderHook |
Testing reusable Hook logic directly | Concise tests for returned values, state changes, and lifecycle behavior. |
| Render a component | Testing how Hook behavior affects the UI | Verifies user-visible behavior such as text, buttons, and form fields. |
For example, a Hook that manages a form can be tested directly to verify its state transitions. A component test can then verify that the user sees validation messages and that submitting the form works correctly.
Best practice: Test the Hook's behavior independently when useful, but also test important user-facing behavior through the components that use it.
14. Common Mistakes When Testing Custom Hooks
Mistake 1: Calling a Hook Directly
Incorrect:
const result = useCounter();
React Hooks must run inside a React component or a custom Hook that is itself called by a component. Call renderHook in the test instead.
Mistake 2: Updating State Without act
When a test invokes a function that triggers a React state update, wrap that operation in act when the testing utility does not already handle it.
act(() => {
result.current.increment();
});
Mistake 3: Using Fixed Delays for Asynchronous Tests
A fixed delay can make tests slow and unreliable. Prefer waitFor or other appropriate asynchronous testing utilities that wait for an expected state.
Mistake 4: Testing Implementation Details
Avoid asserting on internal variables that are not part of the Hook's public behavior. Prefer testing returned values, observable state transitions, and cleanup behavior.
Mistake 5: Forgetting to Clean Up Mocks and Timers
Restore real timers after fake-timer tests and restore or clear mocks between tests. Otherwise, one test can affect another.
Mistake 6: Ignoring React Strict Mode
Strict Mode may run additional Effect setup-and-cleanup cycles in development. Do not assume an Effect must always run exactly once. Test the intended behavior and make sure cleanup is correct.
Mistake 7: Mocking Everything
Mock external dependencies such as network requests when appropriate, but avoid mocking the Hook's own state management. Otherwise, the test may no longer verify the behavior you intended to test.
15. A Practical Custom Hook Testing Checklist
- Test the initial state.
- Test each public operation, such as increment, reset, or toggle.
- Test valid and invalid inputs where applicable.
- Test behavior when props or arguments change.
- Test asynchronous loading, success, and error states.
- Test cancellation or cleanup when the Hook manages external resources.
- Use fake timers for timer-based logic.
- Use
actfor operations that trigger React updates when needed. - Use
waitForfor asynchronous assertions. - Restore mocks, timers, and global stubs after tests.
- Test important user-facing behavior through components as well.
16. Custom Hook Testing Interview Questions
Q1. What is renderHook?
renderHook is a React Testing Library utility that runs a Hook in a test component and exposes its latest returned value.
Q2. Why do we use act?
act ensures that React updates triggered by a test operation are processed before assertions are made.
Q3. How do you test a Hook that fetches data?
Mock the network request, render the Hook, wait for the expected state using utilities such as waitFor, and verify loading, success, and error behavior.
Q4. How do you test a Hook that accepts parameters?
Pass the parameters to renderHook. Use rerender to supply new props when testing how the Hook responds to changing inputs.
Q5. How do you test cleanup logic?
Unmount the Hook using the returned unmount function and verify that resources such as timers or subscriptions are cleaned up.
Q6. Should every custom Hook be tested with renderHook?
No. Some Hooks are best tested through the components that use them, especially when their main purpose is to produce user-visible behavior. Choose the approach that best verifies the intended behavior.
Q7. Can you call a custom Hook directly inside a test?
Not as an ordinary standalone function. A Hook must execute within React's rendering context. Use renderHook or render a component that calls the Hook.
17. Final Summary
- Use
renderHookfrom@testing-library/reactto test custom Hooks directly. - Use
result.currentto inspect the Hook's latest returned values. - Use
actwhen performing operations that trigger React updates. - Use
rerenderto test changes to Hook arguments. - Use
waitForto test asynchronous state changes. - Mock external APIs for predictable unit tests.
- Test cleanup for timers, subscriptions, and other external resources.
- Use fake timers when testing timer-based Hooks.
- Combine direct Hook tests with component tests when both reusable logic and user-facing behavior matter.
The key principle: Test custom Hooks through their observable behavior, including state changes, asynchronous results, and cleanup. This gives you confidence that the Hook works correctly without coupling your tests too tightly to its implementation.
| Why Should Not Call Hooks Conditionally :👈 | 👉:Identify Unnecessary React Re-renders |
Comments and Discussion