QA
Intermediate LevelReact JS & React 19

How do you unit test custom React hooks using React Testing Library?

❓ Interview Prompt: Explain `@testing-library/react`, `renderHook()`, `act()` state wrapping, testing hook returns, and async updates.

Testing custom hooks directly without a component requires '@testing-library/react' 'renderHook':

Key Concepts:

•
'renderHook(() => useMyHook())': Mounts a test component harness executing the hook.
•
'act(() => result.current.action())': Wraps state-mutating hook calls to ensure all React state updates and effects process before assertions execute.

Code Implementation Example

jsx
import { renderHook, act } from '@testing-library/react';
import useCounter from './useCounter';

test('should increment counter state', () => {
  const { result } = renderHook(() => useCounter());

  // Wrap state updates in act()
  act(() => {
    result.current.increment();
  });

  expect(result.current.count).toBe(1);
});
💡Unit testing custom hooks using renderHook and act from React Testing Library.
🎯 Interview Key Takeaway

Use renderHook and wrap state mutations in act() when testing custom React hooks.

#Testing#renderHook#act#Testing Library#Intermediate
Back to all React JS & React 19 Questions→

More React JS & React 19 Interview Questions

Beginner LevelReact JS & React 19

What is JSX and how does it work under the hood?

Beginner LevelReact JS & React 19

What is the difference between props and state in React?

Beginner LevelReact JS & React 19

How does the useState hook work and what is functional updater syntax?