Don't Mock useState or Other Hooks
You'll learn why mocking React's built-in hooks creates unrealistic tests that undermine confidence in your code.
The Core Problem
It's tempting to mock useState, useEffect, or other React hooks to control component behavior during tests. After all, if you want to test a component in a specific state, why not just mock useState to return that state directly?
Because that's not how your component actually works.
When you mock useState, you're testing a fake version of your component—one that doesn't use real React state management. Your test passes, but you've proven nothing about whether your component works in production.
Why It's Like Testing a Cardboard Car
Imagine testing a car's brakes by replacing the entire brake system with a cardboard cutout labeled "brakes work." You press the pedal, the cardboard says "success," but you've learned nothing about actual stopping power.
Mocking hooks does the same thing. You're replacing React's real state management with a test double that behaves differently.
The RTL Approach
React Testing Library's philosophy: interact with components as users do, and let React hooks work normally. If you need a component in a specific state, trigger the user actions that would naturally lead to that state—button clicks, form inputs, waiting for data to load.
// ❌ Don't do this
vi.mock('react', () => ({
...vi.importActual('react'),
useState: vi.fn(() => [mockValue, mockSetter])
}));
// ✅ Do this instead
render(<Counter />);
await userEvent.click(screen.getByRole('button', { name: /increment/i }));
// Now the component is in the desired state naturally
The real hooks test the real component. That's where confidence comes from.
Key Takeaway: Never mock useState, useEffect, or other React hooks—test components with real state by simulating the user interactions that naturally change that state.