Course contentsShow
← React
Lesson 1212 of 2,39631. Forms in ReactFree lesson

useReducer for Complex Form Logic

When form state transitions become intricate, a reducer with action types clarifies state changes and validation flow.

useReducer for Complex Form Logic

What you'll learn: How to manage intricate form state transitions and validations cleanly using a reducer instead of scattered setState calls.

The Problem with Multiple setState Calls

When forms grow complex—tracking multiple fields, validation states, touched flags, and submission status—you end up with a tangle of setState calls scattered throughout your component. Each user action triggers several state updates, making it hard to understand what's actually changing and why.

Why useReducer Clarifies Form Logic

A reducer centralizes all state transitions in one place with explicit action types. Instead of calling setState directly, you dispatch actions like "FIELD_CHANGED", "FIELD_BLURRED", or "VALIDATION_FAILED". The reducer function then handles the complex logic: "When this field changes, update its value, clear its error, mark the form as dirty, and recalculate dependent fields."

This is like having a traffic controller at an intersection versus letting cars figure it out themselves—all the transition rules live in one predictable place.

The Pattern in Practice

function formReducer(state, action) {
  switch (action.type) {
    case 'FIELD_CHANGED':
      return {
        ...state,
        values: { ...state.values, [action.field]: action.value },
        errors: { ...state.errors, [action.field]: null },
        isDirty: true
      };
    case 'FIELD_BLURRED':
      return {
        ...state,
        touched: { ...state.touched, [action.field]: true }
      };
    case 'SET_ERRORS':
      return { ...state, errors: action.errors, isSubmitting: false };
    default:
      return state;
  }
}

Each action type represents a clear state transition. The validation flow becomes explicit: change → clear error → mark dirty. No more hunting through event handlers.

Key Takeaway: When form state transitions involve multiple coordinated updates, useReducer with named action types turns spaghetti logic into a clear, centralized state machine that's easier to reason about and debug.