React / 66
Redux Toolkit: createSlice, configureStore, Provider
One createSlice call gives you a reducer and its action creators. configureStore builds the store, and Provider hands it to your app.
Install
npm install @reduxjs/toolkit react-redux@reduxjs/toolkit builds the store and slices. react-redux connects it to React with Provider, useSelector and useDispatch.
Step 1 · A slice
A slice is one feature's state and the reducers that change it.
you write
Options
name: "cart"initialState: { items: [] }reducers: { addItem, removeItem, clearCart }redux toolkit
createSlice()
you get · slice.actions
Action creators
addItem(dosa)→ { type: "cart/addItem", payload: dosa }you get · slice.reducer
One reducer
import { createSlice } from "@reduxjs/toolkit";
const cartSlice = createSlice({
name: "cart",
initialState: { items: [] },
reducers: {
addItem: (state, action) => {
const found = state.items.find((item) => item.id === action.payload.id);
if (found) found.qty += 1;
else state.items.push({ ...action.payload, qty: 1 });
},
removeItem: (state, action) => {
state.items = state.items.filter((item) => item.id !== action.payload);
},
clearCart: (state) => {
state.items = [];
},
},
});
export const { addItem, removeItem, clearCart } = cartSlice.actions;
export default cartSlice.reducer;Yes, that code "mutates" state. Inside createSlice that's safe: a library called Immer turns it into a proper new state. The next topic explains how.
For each key in reducers, you get an action creator for free:
addItem({ id: 7, name: "Masala Dosa", price: 120 });
// → { type: "cart/addItem", payload: { id: 7, name: "Masala Dosa", price: 120 } }
removeItem(7); // → { type: "cart/removeItem", payload: 7 }
clearCart(); // → { type: "cart/clearCart", payload: undefined }
addItem.type; // "cart/addItem"Whatever you pass in becomes action.payload. The type is the slice name + / + the reducer's key.
Step 2 · The store
import { configureStore } from "@reduxjs/toolkit";
import cartReducer from "./cartSlice";
export const store = configureStore({
reducer: {
cart: cartReducer,
},
});The keys you choose here become the shape of your state: this store's state is { cart: { items: [] } }. Add more slices as more keys.
configureStore also, for free: combines the slice reducers, adds the thunk middleware for async logic, adds development-only checks that catch accidental mutation and non-serializable values (like Promises or class instances in state), and turns on Redux DevTools.
Step 3 · Provide it
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { Provider } from "react-redux";
import { store } from "./store/store";
import App from "./App";
createRoot(document.getElementById("root")).render(
<StrictMode>
<Provider store={store}>
<App />
</Provider>
</StrictMode>
);Header
useSelectorreads the countMenuItem
useDispatchsends addItemCartPage
bothreads items, sends removeItemstore.js
configureStore
reducer: { cart: cartReducer }cartSlice.js
createSlice
export default cartSlice.reducerEvery component inside Provider can now read the store with useSelector and change it with useDispatch. That's the next-but-one topic.
Legacy Redux vs Redux Toolkit
The same "add item" feature, both ways:
import { createStore, combineReducers } from "redux";
// action type + action creator
const ADD_ITEM = "cart/addItem";
const addItem = (item) => ({ type: ADD_ITEM, payload: item });
// reducer: copy every level by hand
function cartReducer(state = { items: [] }, action) {
switch (action.type) {
case ADD_ITEM:
return { ...state, items: [...state.items, action.payload] };
default:
return state;
}
}
// store: createStore is marked deprecated in the redux package
const store = createStore(combineReducers({ cart: cartReducer }));import { configureStore, createSlice } from "@reduxjs/toolkit";
const cartSlice = createSlice({
name: "cart",
initialState: { items: [] },
reducers: {
addItem: (state, action) => {
state.items.push(action.payload);
},
},
});
export const { addItem } = cartSlice.actions;
const store = configureStore({ reducer: { cart: cartSlice.reducer } });Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
