Sub topic 3
Writing a slice with createSlice
This chapter assumes you know React function components and hooks, ES modules, and the idea that reducers are pure functions that return new state. You should also have read the previous chapter on actions, reducers and the store.
What a slice is
A slice is the part of the Redux state that belongs to one feature, together with the logic that updates it. Redux Toolkit's createSlice takes a name, an initial state, and an object of reducer functions. From that it generates the reducer and one action creator for each case reducer.
Without createSlice you write action type strings, action creators, and a switch reducer by hand. createSlice produces all three from one definition.
A first slice
import { createSlice, configureStore } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
incremented(state) {
state.value += 1
},
amountAdded(state, action) {
state.value += action.payload
},
},
})
export const { incremented, amountAdded } = counterSlice.actions
export const store = configureStore({
reducer: {
counter: counterSlice.reducer,
},
})The code inside incremented looks like it mutates state. It does not. Redux Toolkit runs each case reducer through Immer, which turns the "mutation" into a safe immutable update. A later chapter explains how.
What createSlice returns
The slice object has these parts:
| Property | Contents |
|---|---|
| `counterSlice.reducer` | The reducer function to pass to the store |
| `counterSlice.actions` | An object of action creators, one per key in `reducers` |
| `counterSlice.name` | The string `'counter'` |
How action types are named
Each action type is built from the slice name and the reducer key, joined with a slash. The incremented reducer in the counter slice handles counter/incremented.
console.log(incremented())
// { type: 'counter/incremented', payload: undefined }
console.log(amountAdded(5))
// { type: 'counter/amountAdded', payload: 5 }The argument you pass to an action creator becomes action.payload. This is why amountAdded(5) leads to state.value += 5. Because the name is the prefix, two slices can both have a reducer called reset without clashing.
Naming reducers
Name reducers after what happened, not after the setter you want to run. Prefer incremented and todoAdded over setCounter and addTodo. The action log then reads as a history of events, which helps when you debug.
Common errors
- Returning and mutating in the same reducer. Within a case reducer, either mutate the draft or return a new value, never both. Mixing them throws an error.
- Reassigning the
stateargument. Writingstate = { value: 0 }does nothing, because it only rebinds a local variable. Mutate a field or return the new object instead:return { value: 0 }. - Putting the slice in the store but forgetting its key. The key in
configureStore({ reducer: { counter: ... } })decides the pathstate.counter. A mismatch givesundefinedin selectors. - Side effects in reducers. Do not fetch data, generate random values or read the clock in a case reducer. Reducers must be predictable, so do that work before you dispatch.
Exercise
Exercise
You add a reducer reset(state) { state.value = 0 } to the counter slice. What is the type string of the action that reset() creates, and what is its payload?
Show answer
The type is counter/reset, built from the slice name and the reducer key. The payload is undefined, because no argument was passed to the action creator.