Testing Custom Hooks with React Testing Library
Last Updated :
23 Jul, 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
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects