Course contentsShow
← React
Lesson 747 of 2,39620. useReducerFree lesson

When State Logic Becomes Testable Business Logic

Reducers are pure functions that can be tested in isolation without rendering any components.

When State Logic Becomes Testable Business Logic

You'll learn: Why extracting state logic into reducers makes it easier to test your application's business rules without rendering components.

As your React application grows, you'll find that useState spreads business logic across multiple event handlers and effects. Testing this logic becomes challenging because you have to render components, simulate user interactions, and verify state changes through the UI. This tight coupling makes your tests slow and brittle.

The Testing Pain Point

When state updates live inside event handlers scattered throughout your component, testing them means:

  • Rendering the entire component tree
  • Setting up all dependencies (props, context, etc.)
  • Simulating clicks and other events
  • Checking the DOM to verify changes

This is like testing a calculator by clicking physical buttons instead of testing the math functions directly.

The Reducer Solution

When you extract state logic into a reducer function, you create pure, testable business logic. A reducer is just a function that takes the current state and an action, then returns the new state. No components required.

// This is pure business logic - easy to test!
function cartReducer(state, action) {
  switch (action.type) {
    case 'added':
      return [...state, action.item];
    case 'removed':
      return state.filter(item => item.id !== action.id);
    default:
      return state;
  }
}

// Test without any React rendering
test('adding item to cart', () => {
  const result = cartReducer([], { type: 'added', item: { id: 1 } });
  expect(result.length).toBe(1);
});

Your reducer becomes a standalone unit of business logic that you can test independently, document clearly, and reuse across different parts of your app.

Key Takeaway: Reducers are pure functions that can be tested in isolation without rendering any components, making your business logic easier to verify and maintain.