Sub topic 10
Handling actions from other slices with extraReducers
This chapter assumes you can write a slice with createSlice and that you know the Redux flow of dispatch, reducer and new state. It also assumes you know RTK 2.x syntax, where extraReducers takes a builder callback. By the end you will be able to make one slice react to actions it did not define, and you will know the rules that make this safe.
Why a slice needs to react to outside actions
Every action dispatched to a Redux store goes through the root reducer. The root reducer calls every slice reducer with that action. Each slice reducer decides whether to change its own state or ignore the action.
That means more than one slice can respond to the same action. Common cases:
- A
loggedOutaction should clear the todos, the cart and the user profile. - A thunk's
pending,fulfilledandrejectedactions should update a slice that did not create them. - A
userDeletedaction in a users slice should remove that user's posts from a posts slice.
The reducers field of createSlice cannot express this. Each key there creates a new action type prefixed with the slice name. The extraReducers field attaches handlers to action types that already exist.
reducers versus extraReducers
| Field | Generates action creators? | Action type | Typical use |
|---|---|---|---|
| `reducers` | Yes, in `slice.actions` | `name/key`, owned by this slice | Events this slice defines |
| `extraReducers` | No | Any existing action | Events defined elsewhere |
Use reducers for events your slice owns. Use extraReducers for everything else.
The builder callback
extraReducers takes a function. RTK passes it a builder object, and you register handlers by calling methods on it:
builder.addCase(actionCreator, reducer)handles one specific action.builder.addMatcher(matcher, reducer)handles every action for which a function returnstrue.builder.addDefaultCase(reducer)handles any action nothing else matched.
The builder methods can be chained. Their order is enforced: all addCase calls first, then addMatcher calls, then at most one addDefaultCase. RTK throws an error if you call them in another order.
Sharing an action between slices
To handle an action in extraReducers, the slice needs the action creator. It can use the creator itself as the key, because action creators made by RTK have a type string and a match method. addCase reads both.
Put shared actions in their own file. If todosSlice imports from authSlice while authSlice imports from todosSlice, you create a circular import. A neutral file avoids that.
// sharedActions.js
import { createAction } from '@reduxjs/toolkit'
export const loggedOut = createAction('session/loggedOut')
export const sessionExpired = createAction('session/expired')Now a todos slice that clears itself when the user logs out:
// todosSlice.js
import { createSlice } from '@reduxjs/toolkit'
import { loggedOut } from './sharedActions'
const initialState = { items: [], lastError: null }
const todosSlice = createSlice({
name: 'todos',
initialState,
reducers: {
todoAdded(state, action) {
state.items.push(action.payload)
},
},
extraReducers: (builder) => {
builder.addCase(loggedOut, () => initialState)
},
})
export const { todoAdded } = todosSlice.actions
export default todosSlice.reducerThe loggedOut handler returns a value instead of changing state. Immer accepts this: if a reducer returns a new value, that value becomes the next state. Never both change the draft and return a different value. Immer throws an error if you do.
A second slice reacts to the same action in its own way:
// cartSlice.js
import { createSlice } from '@reduxjs/toolkit'
import { loggedOut } from './sharedActions'
const cartSlice = createSlice({
name: 'cart',
initialState: { itemIds: [] },
reducers: {
itemAdded(state, action) {
state.itemIds.push(action.payload)
},
},
extraReducers: (builder) => {
builder.addCase(loggedOut, (state) => {
state.itemIds = []
})
},
})
export const { itemAdded } = cartSlice.actions
export default cartSlice.reducerNeither slice knows about the other. Both only know about loggedOut. This is the main benefit of the pattern: slices stay decoupled, and the action describes what happened rather than which slices should change.
You can verify the behavior by running this file with a bundler or Node ES modules:
// demo.js
import { configureStore } from '@reduxjs/toolkit'
import todosReducer, { todoAdded } from './todosSlice'
import cartReducer, { itemAdded } from './cartSlice'
import { loggedOut } from './sharedActions'
const store = configureStore({
reducer: { todos: todosReducer, cart: cartReducer },
})
store.dispatch(todoAdded({ id: 1, text: 'Write chapter' }))
store.dispatch(itemAdded(42))
console.log(store.getState())
// { todos: { items: [ { id: 1, text: 'Write chapter' } ], lastError: null }, cart: { itemIds: [ 42 ] } }
store.dispatch(loggedOut())
console.log(store.getState())
// { todos: { items: [], lastError: null }, cart: { itemIds: [] } }Matching groups of actions with addMatcher
addCase takes one action. When several actions should trigger the same change, use addMatcher. A matcher is a function that receives an action and returns a boolean. RTK provides helpers to build them, such as isAnyOf and isAllOf.
import { createSlice, isAnyOf } from '@reduxjs/toolkit'
import { loggedOut, sessionExpired } from './sharedActions'
const authSlice = createSlice({
name: 'auth',
initialState: { userId: null, notice: null },
reducers: {
loggedIn(state, action) {
state.userId = action.payload
},
},
extraReducers: (builder) => {
builder.addMatcher(isAnyOf(loggedOut, sessionExpired), (state, action) => {
state.userId = null
state.notice =
action.type === sessionExpired.type ? 'Please sign in again' : null
})
},
})
export const { loggedIn } = authSlice.actions
export default authSlice.reducerA matcher can also test the action type directly. This one matches every rejected async action in the app:
builder.addMatcher(
(action) => action.type.endsWith('/rejected'),
(state, action) => {
state.lastError = action.error?.message ?? 'Unknown error'
}
)Execution order and the default case
For one dispatched action, a slice runs its handlers in a fixed order:
- The matching
reducersoraddCasehandler, if there is one. At most one case handler runs. - Every
addMatcherhandler whose matcher returnstrue, in the order you registered them. Each one receives the state produced by the previous handler. addDefaultCase, but only if no case handler and no matcher ran.
Because several matchers can run for one action, they compose. Case handlers do not. If two addCase calls use the same action type, RTK throws an error in development.
addDefaultCase is rarely needed. A reducer already returns the current state when nothing handles an action, so reserve the default case for things like logging unknown actions during debugging.
Common errors
- Passing
undefinedas the action creator. This usually comes from a circular import, where the imported value is not yet defined whencreateSliceruns. The error mentions that the action type isundefined. Move the shared action into its own file. - Calling
addCaseafteraddMatcher. The builder throws. Reorder the calls. - Expecting an action creator from
extraReducers. Handlers registered there do not appear inslice.actions. Export the creator from where it is defined. - Mutating and returning. A handler that changes
stateand also returns a new object makes Immer throw an error. Choose one. - Matchers that are too broad. A matcher like
() => trueruns on every action in the app, including ones from other slices. Keep matchers specific, because they run on each dispatch. - Using a string type with
addCase.addCase('session/loggedOut', ...)works at runtime, but it loses type inference in TypeScript. Pass the action creator when you have one.
Why this matters for async thunks
The next chapter introduces createAsyncThunk. A thunk creates three actions, pending, fulfilled and rejected, and you handle them with exactly the addCase pattern from this chapter. The thunk is defined outside the slice, so you attach its results with extraReducers. If you are comfortable with addCase and addMatcher here, the thunk lifecycle will look familiar.
Exercise
A posts slice should delete all posts whose authorId equals the id in a userDeleted action from a users slice. The users slice already exports userDeleted from usersSlice.js through usersSlice.actions. usersSlice.js also imports something from postsSlice.js. Where should you define userDeleted to be safe, and how do you write the handler in postsSlice? Assume state.items is an array and the payload is the user id.
Show answer
Move userDeleted into a neutral file such as sharedActions.js using createAction('users/userDeleted'). That removes the circular import between the two slice files, which would otherwise leave userDeleted undefined when postsSlice is evaluated. Then register the handler in the posts slice: extraReducers: (builder) => { builder.addCase(userDeleted, (state, action) => { state.items = state.items.filter((post) => post.authorId !== action.payload) }) }. The users slice can use the same userDeleted action in its own extraReducers to remove the user.
Exercise
A slice has builder.addCase(loggedOut, handlerA) and builder.addMatcher(isAnyOf(loggedOut, sessionExpired), handlerB). In what order do the handlers run when loggedOut() is dispatched, and does an addDefaultCase handler run?
Show answer
handlerA runs first because case handlers run before matchers. Then handlerB runs and receives the state that handlerA produced. The default case does not run, because at least one handler already matched the action.