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

Organizing Reducer, Actions, and Types in One Module

File structure patterns that keep reducer logic, action creators, and TypeScript types cohesive and maintainable.

Organizing Reducer, Actions, and Types in One Module

What You'll Learn

You'll learn a file structure pattern that keeps your reducer logic, action creators, and TypeScript types together in one cohesive module, making your code easier to maintain and reason about.

The Problem with Scattered Code

When using useReducer with Context at scale, you'll have a reducer function, action type constants, action creators, and TypeScript types. Scattering these across multiple files creates navigation overhead—you're constantly jumping between files to understand what actions exist or how the reducer handles them.

The Single Module Pattern

Keep everything related to a single state domain in one file. Think of it like keeping all ingredients and the recipe for one dish in the same place, rather than storing flour in one room, sugar in another, and the instructions in a third.

Here's the structure pattern:

// userState.ts

// 1. TypeScript Types at the top
export type User = { id: string; name: string };
export type State = { user: User | null; loading: boolean };

// 2. Action Types
export type Action =
  | { type: 'USER_LOADED'; payload: User }
  | { type: 'USER_LOADING' };

// 3. Reducer
export function userReducer(state: State, action: Action): State {
  switch (action.type) {
    case 'USER_LOADING':
      return { ...state, loading: true };
    case 'USER_LOADED':
      return { user: action.payload, loading: false };
    default:
      return state;
  }
}

// 4. Action Creators
export const loadUser = (user: User): Action => ({
  type: 'USER_LOADED',
  payload: user
});

export const setLoading = (): Action => ({
  type: 'USER_LOADING'
});

// 5. Initial State
export const initialState: State = {
  user: null,
  loading: false
};

Everything you need to understand userReducer is in one scrollable view.

Key Takeaway: Organizing your reducer, actions, types, and action creators in a single module creates a cohesive "state domain" that's easier to understand, test, and maintain—you see the entire state story in one place.