Course contentsShow
← React
Lesson 2376 of 2,39651. TypeScript with React BasicsFree lesson

Typing Context with useReducer Actions

Properly typing dispatch functions when using useReducer, including discriminated union action types.

Typing Context with useReducer Actions

You'll learn how to properly type a Context provider that uses useReducer, ensuring your dispatch function and action types are type-safe throughout your app.

The Core Idea

When you combine Context with useReducer, you're typically sharing both state and a dispatch function. TypeScript needs to understand what actions your reducer accepts so it can catch errors when you dispatch the wrong action type or forget required payload properties.

The key is using discriminated unions for your action types. Each action has a type property that acts as the discriminator, and TypeScript uses that to narrow down which payload properties are valid.

The Pattern

// Define your actions as a discriminated union
type CounterAction =
  | { type: 'increment' }
  | { type: 'decrement' }
  | { type: 'set'; payload: number }
  | { type: 'incrementBy'; payload: number };

type CounterState = { count: number };

// Reducer knows all possible actions
const counterReducer = (state: CounterState, action: CounterAction): CounterState => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'set':
      return { count: action.payload }; // TypeScript knows payload exists here
    default:
      return state;
  }
};

// Context type includes dispatch with the action union
type CounterContextType = {
  state: CounterState;
  dispatch: React.Dispatch<CounterAction>;
};

const CounterContext = createContext<CounterContextType | undefined>(undefined);

Now when consumers call dispatch({ type: 'set' }), TypeScript will error because payload is missing. When they write dispatch({ type: 'increment' }), it knows no payload is needed.

Key Takeaway: Type your reducer actions as a discriminated union, then use React.Dispatch<YourActionUnion> for the dispatch function in your Context type—TypeScript will enforce correct action shapes everywhere you dispatch.