How to Mock useDeferredValue in React
Testing React components that utilize the
useDeferredValue hook can be challenging because of its
asynchronous, non-blocking behavior. This article provides a quick guide
on how to mock the useDeferredValue hook using Jest or
Vitest to make your unit tests predictable, synchronous, and easy to
assert.
Why Mock useDeferredValue?
The useDeferredValue hook is designed to defer updating
a state value until more urgent render passes are complete. In a testing
environment, this deferred behavior can introduce timing issues,
requiring complex asynchronous utilities or causing test flakiness. By
mocking the hook to immediately return the input value, you can test
your component’s rendering logic synchronously.
Mocking React’s Hook with Jest or Vitest
To mock useDeferredValue, you need to mock the
react package. The mock should preserve all other React
exports while overriding useDeferredValue to act as an
identity function, which simply returns whatever value is passed into
it.
Add the following mock definition at the top of your test file, before any component imports:
jest.mock('react', () => {
const originalReact = jest.requireActual('react');
return {
...originalReact,
useDeferredValue: jest.fn((value) => value),
};
});Note: If you are using Vitest, replace jest.mock
with vi.mock and jest.requireActual with
vi.importActual.
Example Implementation
Consider a simple search component that defers the search query to keep the UI responsive:
import React, { useDeferredValue } from 'react';
export function SearchResults({ query }) {
const deferredQuery = useDeferredValue(query);
return <div data-testid="results">Results for: {deferredQuery}</div>;
}With the mock defined above, your unit test can assert the rendered output directly without waiting for transition timing:
import React from 'react';
import { render, screen } from '@testing-library/react';
import { SearchResults } from './SearchResults';
jest.mock('react', () => ({
...jest.requireActual('react'),
useDeferredValue: (value) => value,
}));
test('renders deferred query immediately when mocked', () => {
render(<SearchResults query="React Hooks" />);
const element = screen.getByTestId('results');
expect(element).toHaveTextContent('Results for: React Hooks');
});By bypassing the deferral mechanism during testing, your tests remain fast, deterministic, and free of unnecessary timing boilerplates.