extraReducers lets a slice respond to actions it did not define in its own reducers field. Unlike reducers, it generates no action creators or action types. It only adds handlers for actions that already exist.
Use it for:
- the
pending,fulfilledandrejectedactions of acreateAsyncThunk - actions defined by another slice, like resetting state on logout
- RTK Query endpoint matchers
You write it with the builder callback. addCase handles one action type, addMatcher handles a range of actions, and addDefaultCase handles the rest. The old object notation was removed in Redux Toolkit 2.0, so the builder is the only form.
const userSlice = createSlice({
name: 'user',
initialState: { data: null, loading: false },
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchUser.pending, (state) => {
state.loading = true;
})
.addCase(fetchUser.fulfilled, (state, action) => {
state.data = action.payload;
state.loading = false;
});
}
});
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓