Course contentsShow
← React
Lesson 2121 of 2,39647. Testing Patterns and Best PracticesFree lesson

Hook Implementation Should Be Invisible

Tests should work the same whether a component uses useState, useReducer, or any other hook internally.

Hook Implementation Should Be Invisible

What you'll learn: How to write tests that remain valid regardless of which hook a component uses internally.

The Core Principle

Your tests should care about what a component does, not how it achieves it. Whether a component manages state with useState, useReducer, useSyncExternalStore, or a custom hook is an implementation detail. A well-written test works unchanged even when you refactor from one hook to another.

Why This Matters

Imagine testing a counter component. If your test checks "does useState get called?" or "is there a count state variable?", it breaks the moment you refactor to useReducer for better update logic. The user doesn't care which hook you used—they only care that clicking the button increments the number on screen.

The Right Approach

Test the observable behavior:

// ✅ Hook-agnostic: tests what the user sees
test('increments count when button clicked', async () => {
  const user = userEvent.setup();
  render(<Counter />);
  
  expect(screen.getByText('Count: 0')).toBeInTheDocument();
  await user.click(screen.getByRole('button', { name: /increment/i }));
  expect(screen.getByText('Count: 1')).toBeInTheDocument();
});

This test passes whether the component uses useState, useReducer, or even fetches count from an external store. You're testing the rendered output and user interactions, not the mechanism behind them.

The Analogy

Think of a car's dashboard. You test that the speedometer shows correct speed when you accelerate. You don't test whether it's using a cable, electronic sensor, or GPS internally—that's the manufacturer's concern.

Key Takeaway: Write tests against the component's public interface (props in, DOM out, user interactions). Hook choice is a private implementation detail that should be invisible to your test suite.