createSlice turns a slice name, an initial state and an object of reducer functions into a slice reducer plus an action creator for each reducer. It returns them in one object, which removes the hand-written action types and switch statements of classic Redux.
How it works:
- Each key in
reducersbecomes an action type prefixed with the slice name, such as'counter/increment'. - Each case reducer is wrapped in Immer, so it can "mutate"
stateand still produce an immutable update. extraReducersadds handlers for actions defined elsewhere, like thunk results, without generating new action creators.
The returned object holds:
reducer, the slice reducer to pass toconfigureStoreorcombineReducersactions, an action creator for each case reducer, usually exported by destructuringname, the slice namegetInitialState, a function that returns the initial statecaseReducers, the original reducer functionsselectors, for any selectors you define
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value += 1; // Immer makes this safe
},
incrementByAmount: (state, action) => {
state.value += action.payload;
}
}
});
// Returns: { reducer, actions: { increment, incrementByAmount } }
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 ↓