Sub topic 3
Writing a slice with createSlice
This chapter assumes you know the Redux model from the previous chapter: a store holds state, actions describe what happened, and reducers compute the next state. It also assumes you are comfortable with ES modules, destructuring and spread syntax, and the idea that reducers must not modify their input. Here you will write your first slice and learn what createSlice generates for you.
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. In a todo app you might have a todos slice and a user slice. Each one owns one key of the root state object.
Without Redux Toolkit, one slice needs several separate pieces: action type strings, action creator functions, a switch statement in a reducer, and manual immutable copying. createSlice takes one definition and produces the action creators and the reducer.
The three required options
createSlice takes an object with three required fields.
nameis a string used as the prefix of every action type. It should be unique across your store.initialStateis the state value the reducer uses when the store starts and no state exists yet.reducersis an object of case reducers. Each key becomes both a function name and part of an action type.
Here is a complete counter slice with a store:
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 configureStore call is covered in detail in a later chapter. For now, treat it as the step that registers the slice reducer under the key counter.
What gets generated
For each key in reducers, createSlice builds an action creator with the same name. The action type is name/key.
You can check this by calling the action creators:
import { incremented, amountAdded } from './counterSlice'
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. The slice only ever uses one argument, so if you need several values, pass a single object.
The reducer can also be called directly, because it is a plain function:
import counterSlice, { incremented, amountAdded } from './counterSlice'
const reducer = counterSlice.reducer
let state = reducer(undefined, { type: 'unknown' })
console.log(state) // { value: 0 }
state = reducer(state, incremented())
state = reducer(state, amountAdded(5))
console.log(state) // { value: 6 }This assumes you also add export default counterSlice to the slice file. Calling a reducer with undefined as the state returns initialState. Redux does exactly this when the store starts. Being able to call the reducer like this is also what makes slices easy to test.
Case reducers
Each function inside reducers is a case reducer. It handles one kind of action. It receives the current slice state and the action, and it either modifies the state or returns a new value.
Inside a case reducer you can write state.value += 1. This looks like mutation, but createSlice runs case reducers through Immer, which records your changes and produces a new immutable state. The next chapter explains how this works and where it stops working. For now, remember two rules:
- Either modify
stateor return a new value, never both in the same call. - Modify
statedirectly only inside case reducers. Outside of them, keep treating state as read-only.
Returning a value replaces the whole slice state. That is useful for a reset:
import { createSlice } from '@reduxjs/toolkit'
const initialState = { value: 0, step: 1 }
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
stepChanged(state, action) {
state.step = action.payload
},
reset() {
return initialState
},
},
})
export const { stepChanged, reset } = counterSlice.actions
export default counterSlice.reducerThe reset reducer takes no arguments because it does not need the old state or the action.
Naming reducers as events
Redux action names should describe what happened, not a command to run. Prefer incremented, todoAdded and userLoggedOut to increment, addTodo and logout. The reducer then decides what that event means for its state. This also keeps the Redux DevTools action log readable: todos/todoAdded tells you what the user did.
This is a convention recommended by the Redux team, and RTK does not enforce it. Keep the naming consistent within your project.
Customizing the payload with prepare
By default the action creator puts its first argument into payload. Sometimes you need to compute values before the action is created, such as a random ID. Reducers must be pure, so they cannot generate random values. The prepare callback does this work before the action reaches the reducer.
To use it, replace the reducer function with an object that has reducer and prepare fields:
import { createSlice, nanoid } from '@reduxjs/toolkit'
const todosSlice = createSlice({
name: 'todos',
initialState: { items: [] },
reducers: {
todoAdded: {
reducer(state, action) {
state.items.push(action.payload)
},
prepare(text) {
return {
payload: { id: nanoid(), text, completed: false },
}
},
},
todoToggled(state, action) {
const todo = state.items.find((t) => t.id === action.payload)
if (todo) {
todo.completed = !todo.completed
}
},
},
})
export const { todoAdded, todoToggled } = todosSlice.actions
export default todosSlice.reducerCalling todoAdded('Write chapter') now produces an action with a payload { id, text, completed }. The caller passes only the text. The ID is generated before dispatch, so the reducer stays pure and the action log shows the exact ID that was used.
The prepare function must return an object with a payload field. It can also return meta and error fields.
What a slice does not handle
The reducers field only responds to actions that the slice itself defines. If a slice must react to an action created elsewhere, for example a userLoggedOut action from another slice, use the extraReducers option. That option, and its use with async actions, is covered in a later chapter.
Common errors
- Exporting the wrong thing. The slice object is not a reducer. Pass
slice.reducerto the store, notslice. Actions come fromslice.actions, not from the slice object itself. - Reassigning
state. Writingstate = { value: 0 }inside a case reducer does nothing, because it only changes the local variable. Return the new value instead, asresetdoes above. - Duplicate slice names. Two slices named
countergenerate identical action types, so both reducers could react to the same action. Keep names unique. - Random or time-based values in reducers. Calls to
Math.random(),Date.now()ornanoid()inside a case reducer make it impure. Move them intoprepare. - Non-serializable payloads. Putting class instances, functions or
Dateobjects in actions or state triggers warnings from the store's default checks. Use plain objects, strings and numbers, such as an ISO date string.
Summary of options
| Field | Required | Purpose |
|---|---|---|
| `name` | Yes | Prefix for generated action types |
| `initialState` | Yes | State used when the store starts |
| `reducers` | Yes | Case reducers that also generate action creators |
| `extraReducers` | No | Responds to actions defined outside the slice |
Exercise
A slice named cart has a case reducer called itemRemoved. What is the action type string generated for it? A teammate writes itemRemoved(state, action) { state = state.filter((i) => i.id !== action.payload) } where state is an array. Why does this reducer have no effect, and how do you fix it?
Show answer
The action type is cart/itemRemoved. The reducer has no effect because assigning to the state parameter only changes the local variable, and nothing is returned, so Immer sees no change. Fix it by returning the new array: return state.filter((i) => i.id !== action.payload). Alternatively, find the index and call state.splice(index, 1), which modifies the draft in place.
Exercise
You want a noteAdded action where the caller passes only the note text, and each note gets an id and a createdAt timestamp as an ISO string. Where should the id and timestamp be created, and why?
Show answer
Create them in a prepare callback, not in the reducer. Reducers must be pure, so they cannot call nanoid() or new Date(). Define noteAdded: { reducer(state, action) { state.items.push(action.payload) }, prepare(text) { return { payload: { id: nanoid(), text, createdAt: new Date().toISOString() } } } }. The values are computed once before dispatch, and the string timestamp keeps the payload serializable.