createSlice
- React course
- Advanced
- Lesson 22/56
- 4 min
Learn to write a slice and its reducer.
createSlice details
createSlice auto-generates an action creator for every function you define inside reducers. If the function is addItem, the action type becomes cart/addItem.
Thanks to immer, RTK allows mutations like state.items.push(...); you write normal-looking JS, but the state is still updated immutably.
To dispatch an action you call dispatch(addItem(product)); the payload is added automatically.
Immutability with immer
RTK uses the immer library. So you can write state.items.push(...) inside a reducer; immer turns the mutation into a new state behind the scenes.
This removes the classic Redux spread chaos like { ...state, items: [...state.items, payload] }. The code becomes more readable.
Immer works with proxies; it copies only the changed branches and shares the rest. This keeps performance high.
Practice Define productSlice
Complete the skeleton. Define productSlice with createSlice. name: 'product', initialState: { list: [] }, inside reducers add addProduct (state, action) => state.list.push(action.payload). Add export const { addProduct } = productSlice.actions; and export default productSlice.reducer;.
Starter code
import { createSlice } from '@reduxjs/toolkit';
// Define productSlice hereSample solution
import { createSlice } from '@reduxjs/toolkit';
const productSlice = createSlice({
name: 'product',
initialState: { list: [] },
reducers: {
addProduct: (state, action) => {
state.list.push(action.payload);
},
},
});
export const { addProduct } = productSlice.actions;
export default productSlice.reducer;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does createSlice auto-generate?
Each reducer function becomes an action creator.- The store
- Action creators Correct answer
- CSS files
- Test files
Explanation: createSlice auto-generates action creators.
2 push inside reducer
addItem: (state, action) => { state.items.____(action.payload); }
addItem: (state, action) => { state.items.push(action.payload); }
Explanation: push adds the item to the array.
3 createSlice: match the terms
| Term | Meaning |
|---|---|
createSlice |
Creates slice |
immer |
Immutability |
addItem |
Action creator |
dispatch |
Sends action |