Define a feature module
A counter, form, or preferences feature needs local Redux state and update actions.
Redux Toolkit · Type Alias
createSlice defines a feature's state and case reducers, then generates its reducer, action creators, and action types. It is Redux Toolkit's standard way to package Redux logic for one slice of state.
A slice packages one feature's state update logic with the actions that trigger it. createSlice receives a name, initial state, and case reducers; it returns a slice object containing the combined reducer, generated action creators, action type information, and case reducers.
createSlice({ name, initialState, reducers, extraReducers? })| Name | Type | Description |
|---|---|---|
options | CreateSliceOptions<State, CaseReducers, Name> | Configuration object containing the slice name, initial state, reducer cases, and optionally extraReducers. |
A slice object containing the generated reducer, action creators, action types, and case reducers.
import { createSlice, type PayloadAction } from '@reduxjs/toolkit'
type CounterState = { value: number }
const initialState: CounterState = { value: 0 }
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment(state) {
state.value += 1
},
add(state, action: PayloadAction<number>) {
state.value += action.payload
},
},
})
export const { increment, add } = counterSlice.actions
export default counterSlice.reducerCreates a typed counter slice, then exports its generated action creators and reducer.
A counter, form, or preferences feature needs local Redux state and update actions.
Several feature reducers need to be registered in one Redux store.
A slice must react to actions emitted by another slice or middleware.
A reducer needs concise immutable updates for nested state.
createSlice takes one configuration object containing a name, initialState, and reducers. It returns a slice reducer and matching action creators, while internally using createAction and createReducer.
Follow-up: How can a slice respond to an action it did not generate? Use extraReducers to add handlers for external action types.
Each key in reducers defines a case reducer. Redux Toolkit uses the slice name and reducer key to form the action type, and creates an action creator for that case reducer.
Follow-up: What does the generated action type look like? It combines the name and reducer key, such as test/increment.
Reducer code may use mutating syntax because Redux Toolkit uses Immer internally. Immer converts those apparent mutations into immutable state updates.
Follow-up: What must a reducer avoid when using this style? It should not both mutate the draft state and return a separate new state value in the same case reducer.
createActioncreateReducerconfigureStorecombineReducersextraReducersPayloadAction