Slices: State + Reducers + Actions Together
You'll learn how Redux Toolkit's createSlice bundles your state, reducers, and action creators into one cohesive unit, eliminating boilerplate.
The All-in-One Solution
In traditional Redux, you'd write action types as constants, action creators as functions, and reducers in a separate file—all for a single feature. Redux Toolkit's createSlice changes this by letting you define everything in one place.
Think of a slice like a pre-packaged meal kit: instead of buying ingredients separately (actions here, reducers there, state elsewhere), you get everything needed for one feature together.
How createSlice Works
You call createSlice with an object containing:
- name: A string identifying this slice (e.g.,
"counter") - initialState: Your feature's starting state
- reducers: An object where each key becomes both a reducer case AND an auto-generated action creator
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value += 1; // Immer makes this safe!
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
}
}
});
Redux Toolkit automatically generates:
- Action creators:
counterSlice.actions.increment() - Action types:
"counter/increment" - A reducer:
counterSlice.reducer
Export the actions for components and the reducer for your store:
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
Key Takeaway: createSlice eliminates Redux boilerplate by co-locating state, reducers, and action creators in one declaration, auto-generating actions and using Immer for safe mutations.