Testing Custom Hooks with React Testing Library
Last Updated :
15 Apr, 2025
React hooks fall into two categories: built-in hooks provided by React itself and custom hooks, which are user-defined functions. The most commonly used built-in hooks are useState, useEffect, useMemo, and useCallback. Custom hooks in React are JavaScript functions that allow you to excerpt and reuse stateful logic from components.
They allow us to create reusable behaviour that can be used inside various components, thus minimizing code duplication. We can use other Hooks inside Custom hooks. Hook names start with use followed by a capital letter, like useState,useMemo (built-in), or useValidateImageUrl(custom).
In this article, we'll discuss the process of testing React Hooks. We'll create a custom hook and focus on creating test cases.
Pre-requisites:
Introduction and Testing
The react-hooks-testing-library provides functionalities for rendering custom hooks in test environment and asserting their result in different use cases.
Using this library, You do not have to worry about how to construct, render or interact with the react component in order to test your hook. You can just use the hook directly and test the results.
This library provides a testing experience as near as possible to natively using your hook from within a real component.
Here is an overview of the APIs provided by the library`@testing-library/react-hooks`:
renderHook(callback: (props?: any) => any): RenderHookResult
Renders a custom hook inside a test. It will return an object containing properties and methods that you can use to interact with the rendered hook.
act(callback: () => void | Promise<any>): void
Wrap interactions with hooks inside act() to ensure proper execution of the callback and synchronisation with React's update cycle.
act() helps make your tests run similar to what real users experience when using your application.
Approach:
- Initialize a React App: Start by creating a new React application using a tool like Create React App. It will set up the basic structure and dependencies reuired for your project. It helps you to create and run React project very quickly.
- Create Custom Hooks: Write the custom hooks that you want to add in your application. These hooks contain reusable logic that can be shared by many components.
- Setup Testing Dependencies: Install the necessary testing packages such as Jest and React Testing Library. These tools provide utilities for running tests for your React components and hooks.
- Write Tests for Custom Hooks: Create test files for your custom hooks. Write test cases to verify the behavior of each hook function, including test cases and expected outputs.
- Mock Dependencies (if needed): If your custom hooks depend on external resources or APIs, you may require to mock them in your tests to isolate the behavior of the hook.
- Run Tests: Execute your test suite to ensure that all tests pass and your custom hooks behave as expected.
- Integrate Hooks into Components: Use your custom hooks within your React components to leverage the shared logic they provide.
- Write Component Tests (optional): If your components utilize custom hooks extensively, you may want to write integration tests for the components to ensure they work correctly with the hooks.
Examples:
Initialize a new React project :
npm create react-app custom-hooks-example
cd custom-hooks-example
Install @testing-library/react-hooks for testing our custom hook :
// if you're utilizing npm
npm install --save-dev @testing-library/react-hooks
// or if you're utilizing yarn
yarn add --dev @testing-library/react-hooks
Note: We will add @testing-library/react-hooks as DevDependency because a developer needs this package during development and testing.
List of devDependancies in package.json as shown below:
gfg:package-json-file-structureFolder structure:
gfg: React app Folder StructureExample: To demonstrate testing custom hooks with react testing library.
JavaScript
// Filename : useCounter.js
import { useState } from 'react';
const useCounter = (startValue = 0, step = 1) => {
const [count, setCount] = useState(startValue);
const increment = () => {
setCount(count + step);
};
const decrement = () => {
setCount(count - step);
};
return { count, increment, decrement };
};
export default useCounter;
JavaScript
// Filename : Counter.js
import React from 'react';
import useCounter from './useCounter';
const Counter = () => {
const { count, increment, decrement } = useCounter();
return (
<>
<h2>Count: {count}</h2>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</>
);
};
export default Counter;
JavaScript
// Filename : useCounter.test.js
import { renderHook, act } from '@testing-library/react-hooks';
import useCounter from './useCounter';
test('should use counter', () => {
const { result } = renderHook(() => useCounter());
expect(result.current.count).toBe(0);
expect(typeof result.current.increment).toBe('function');
})
test('should increment count by 1', () => {
const { result } = renderHook(() => useCounter());
act(() => result.current.increment());
expect(result.current.count).toBe(1);
});
test('should decrement count by 1', () => {
const { result } = renderHook(() => useCounter());
act(() => result.current.decrement());
expect(result.current.count).toBe(-1);
});
test('should increment count by custom step', () => {
const { result } = renderHook(() => useCounter(0, 2));
act(() => result.current.increment());
expect(result.current.count).toBe(2);
});
Run the tests to make sure everything is working correctly:
npm test
Output:

To test useCounter ,we will render it using the renderHook function provided by react-hooks-testing-library.
In the first test case, the result's current value matches the initial value what is returned by the hook.
In the second test case, After increment function is called, the current count value reflects the new value returned by the hook.
We have wrapped the increment call inside act().
Similar Reads
How To Test React App With Jest and React Testing Library?
Jest is a JavaScript testing framework maintained by Facebook, designed with a focus on simplicity and support for large JavaScript applications, especially React. It offers built-in utilities like test runners, mocking, snapshot testing, and code coverage reporting. React Testing Library (RTL) is a
3 min read
When to Choose Enzyme Over React Testing Library?
When it comes to testing React components, developers often face the dilemma of choosing between Enzyme and React Testing Library (RTL). Both libraries serve the purpose of testing React components, but they have different philosophies and approaches. In this article, we'll explore the scenarios in
4 min read
7 Common Testing Libraries/Frameworks used with React-Redux
Testing is a critical aspect of software development, ensuring that applications behave as expected and meet quality standards. In React-Redux applications, where state management plays a crucial role, effective testing becomes even more important. Fortunately, there are several testing libraries an
4 min read
Compare React Testing Library and Enzyme for Testing React Components.
React Testing Library and Enzyme are widely used testing utilities for React components. Although they serve the same purpose, their approaches and features differ. React Testing LibraryReact Testing Library is a lightweight testing utility for React. It emphasizes testing components from the user's
4 min read
Building Custom Hooks Library in React
Custom hooks in React allow developers to encapsulate and reuse logic, making it easier to manage state and side effects across multiple components. As applications become complex, developers often repeat similar patterns for state management, API calls, or event handling. This can lead to code dupl
4 min read
What are queries in React Testing Library ?
In this article, we explain the concept of queries in the React Testing Library. Ensuring that components behave as expected when developing applications with React is crucial. One powerful tool for testing React components is the React Testing Library. At the heart of the React Testing Library lies
3 min read
Building a Component Library with React Hooks and Storybook
Building a component library is a powerful way to streamline the development process, ensure consistency across projects, and promote the reusability of UI elements. In this article, we'll explore how to create a component library using React Hooks and Storybook, a tool for developing UI components
3 min read
Commonly used tools for testing in React
Testing is a critical aspect of building reliable and maintainable React applications. Several tools and libraries are commonly used for testing in the React ecosystem, covering unit testing, integration testing, and end-to-end testing. Some popular tools for testing in React:Jest: Jest is a widely
2 min read
Theming and Dark Mode with React Hooks
React Hooks are a feature introduced in React 16.8 that enable functional components to use state and other React features without writing classes. They provide a way to manage component state, perform side effects, access context, and more within functional components, offering a simpler and more i
3 min read
How to Test React Components using Jest ?
React is a frontend open-source JavaScript library, used to build interactive User Interfaces. React is focused on Single Page applications and is more popularly known as a SPA. Testing is an important aspect of development. It examines whether the application is behaving as intended, and protects
6 min read