Course contentsShow
← React
Lesson 1735 of 2,39641. State Management EcosystemFree lesson

extraReducers: Responding to External Actions

Handling actions from other slices or async thunks using the builder callback pattern in extraReducers.

extraReducers: Responding to External Actions

What You'll Learn

You'll learn how to make one slice respond to actions from other slices or async thunks using the extraReducers field with the builder callback pattern.

The Core Idea

Within Redux Toolkit, each slice creates its own actions through reducers. But what if your userSlice needs to react when authSlice logs someone out? Or when an async thunk from another file completes? That's where extraReducers comes in.

The extraReducers field lets you listen to actions you didn't define in your slice—actions from other slices or async thunks created elsewhere. You use a builder callback pattern to specify which external actions trigger state updates in your slice.

The Builder Callback Pattern

Instead of an object, extraReducers takes a function that receives a builder:

import { createSlice } from '@reduxjs/toolkit';
import { logout } from './authSlice';
import { fetchUserProfile } from './userThunks';

const profileSlice = createSlice({
  name: 'profile',
  initialState: { data: null, status: 'idle' },
  reducers: {
    clearProfile: (state) => {
      state.data = null;
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(logout, (state) => {
        // Respond to authSlice's logout action
        state.data = null;
        state.status = 'idle';
      })
      .addCase(fetchUserProfile.fulfilled, (state, action) => {
        // Respond to async thunk completion
        state.data = action.payload;
        state.status = 'succeeded';
      });
  }
});

The builder provides .addCase() to listen for specific action types. You can respond to regular actions or the generated actions from createAsyncThunk (pending, fulfilled, rejected).

Why It Matters

This pattern keeps slices decoupled yet responsive. Your profile slice doesn't need to import or control logout—it just reacts when that action happens anywhere in the app.

Key Takeaway: Use extraReducers with the builder callback to make slices respond to external actions from other slices or async thunks, maintaining separation while enabling cross-slice coordination.