Appearance
6.4.7 — Redux Toolkit, Step by Step
The shop's cart is needed in three places that are far apart. The header shows how many items it holds. Every product card has an "Add to cart" button. The checkout page lists the items and their total.
On page 6.4.2 you solved this by putting the cart in a parent and passing it down. That works for two or three levels. With ten levels, you pass the cart through eight components that never look at it. Page 6.4.6 explained the options. This page teaches the most widely used one, Redux Toolkit, by building the shop's cart with it, one small step at a time.
1. The idea, with a bank
Think of a bank. The bank keeps one ledger. Nobody is allowed to walk in and scribble in the ledger. If you want to change your balance, you fill in a slip that says what you want, such as "deposit 10". You hand it to the teller. The teller follows a fixed rule book and writes the new balance.
Redux uses the same three parts.
| In the bank | In Redux | What it is |
|---|---|---|
| The ledger | State (kept in the store) | One object that holds the data of the whole app |
| The slip | Action | A plain object that says what happened |
| The teller with the rule book | Reducer | A function that takes the old state and an action, and returns the new state |
The word dispatch means "hand the slip to the teller". Components never change the state themselves. They only dispatch actions. Here is the loop.
Follow the numbers. A button calls dispatch with an action (①). The store passes the action to the reducer (②). The reducer returns the new state and the store keeps it (③). Components that select a piece of that state check whether their piece changed (④). Those that changed draw again (⑤).
Why so strict? Because every change now has a name and a record. You can print every action the app ever received. When a bug appears, you can read the list and see exactly what happened and in which order. This is the whole reason Redux exists.
Redux Toolkit (RTK) is the official, modern way to write Redux. Old Redux needed a lot of repeated code. RTK removes most of it. You will not meet the old style in this book.
2. Install it
bash
npm install @reduxjs/toolkit react-reduxTwo packages, two jobs. @reduxjs/toolkit is the store and the tools to write reducers. react-redux connects the store to React components (the Provider and the hooks).
3. Step 1: write a slice
A slice is one feature's part of the state, together with the actions that can change it. Our feature is the cart.
ts
// src/features/cart/cartSlice.ts
import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
export type CartItem = {
productId: string
name: string
priceCents: number
quantity: number
}
type CartState = { items: CartItem[] }
const initialState: CartState = { items: [] } // (1)
const cartSlice = createSlice({
name: 'cart', // (2)
initialState,
reducers: {
itemAdded(state, action: PayloadAction<Omit<CartItem, 'quantity'>>) { // (3)
const existing = state.items.find((i) => i.productId === action.payload.productId)
if (existing) {
existing.quantity += 1 // (4)
} else {
state.items.push({ ...action.payload, quantity: 1 })
}
},
itemRemoved(state, action: PayloadAction<string>) {
state.items = state.items.filter((i) => i.productId !== action.payload)
},
quantityChanged(state, action: PayloadAction<{ productId: string; quantity: number }>) {
const item = state.items.find((i) => i.productId === action.payload.productId)
if (item) item.quantity = action.payload.quantity
},
cartCleared() {
return initialState // (5)
},
},
})
export const { itemAdded, itemRemoved, quantityChanged, cartCleared } = cartSlice.actions // (6)
export default cartSlice.reducer // (7)Walk through it in order.
initialStateis what the cart looks like when the app starts: an empty list.name: 'cart'is a prefix. Every action this slice makes gets a type that starts with it, such as'cart/itemAdded'. That keeps names from clashing with other slices.- Each function under
reducersis one kind of change. It receives the currentstateand anaction.PayloadAction<...>is the TypeScript type of the action. The payload is the data you send with it. Here it is "the product to add, without a quantity".Omit<CartItem, 'quantity'>means "a CartItem except for thequantityfield". - Look closely. This line changes
existing.quantitydirectly, which on page 6.4.2 we said you must never do. In Redux Toolkit it is allowed. The next section explains why. - A reducer can instead return a whole new state. Here it throws everything away and returns to the start.
createSlicewrites the action creators for you, one for each reducer, with the same name. An action creator is a function that makes an action object.itemAdded(product)returns{ type: 'cart/itemAdded', payload: product }. We checked this by printing it.- The slice's reducer is the default export. The store will use it.
"But you said never mutate!" Immer
Line (4) looks like the forbidden thing. It is safe because of a library called Immer that Redux Toolkit uses inside createSlice.
Here is what really happens. Redux Toolkit does not give your reducer the real state. It gives a draft, which is like a photocopy of the state with a note-taker watching you. When you write existing.quantity += 1, you are scribbling on the photocopy. The note-taker writes down "quantity changed on this item". When your function ends, Immer uses the notes to build a brand new state that has only those changes. The real old state is never touched. Everything you did not change is reused as it was, so it is cheap.
So you get two things at once: code that reads like a normal change, and a result that follows the "never change, always replace" rule. We checked that the array after two adds is a new array and not the old one.
There is one rule you must follow, and Immer enforces it. In one reducer, either change the draft, or return a new value. Never do both. When we tried both, Immer threw this error:
text
[Immer] An immer producer returned a new value *and* modified its draft.
Either return a new value *or* modify the draft.Use the first style (change the draft) for small edits, and the second (return ...) when you replace the whole state, as cartCleared does. Immer only works inside createSlice reducers. Everywhere else in your app, the "never mutate" rule from page 6.4.2 still applies.
4. Step 2: create the store
The store holds the state and the reducers. You create it once.
ts
// src/store.ts
import { configureStore } from '@reduxjs/toolkit'
import cartReducer from './features/cart/cartSlice'
export const store = configureStore({
reducer: {
cart: cartReducer, // (1)
},
})
export type RootState = ReturnType<typeof store.getState> // (2)
export type AppDispatch = typeof store.dispatch // (3)- The keys of
reducerbecome the keys of the state. The whole state is now{ cart: { items: [...] } }. When you add aproductsslice later, it becomes another key here.configureStorealso turns on helpful checks in development, such as a warning if you put a value that cannot be saved as JSON into the state. RootStateis the TypeScript type of the whole state. It is worked out from the store, so it can never disagree with it.AppDispatchis the type of thedispatchfunction. It will know about every kind of action your store accepts.
5. Step 3: make typed hooks
React-Redux gives you two hooks. useSelector reads from the state. useDispatch gets the dispatch function. By default, they do not know your types. You fix that once, in one small file, and use your own versions everywhere.
ts
// src/hooks.ts
import { useDispatch, useSelector } from 'react-redux'
import type { AppDispatch, RootState } from './store'
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
export const useAppSelector = useSelector.withTypes<RootState>()Now useAppSelector((state) => state.cart.items) knows that state.cart.items exists and what it holds. If you mistype state.card, TypeScript tells you.
6. Step 4: give React the store
tsx
// src/main.tsx
import { createRoot } from 'react-dom/client'
import { Provider } from 'react-redux'
import { store } from './store'
import App from './App'
createRoot(document.getElementById('root')!).render(
<Provider store={store}>
<App />
</Provider>,
)Provider is a component that makes the store available to every component below it. It uses React's Context inside (page 6.4.6), but it only puts the store object in the context, and the object never changes. That is why it does not cause the re-render problem that putting the state itself in a context would.
7. Step 5: use it in components
Now any component, at any depth, can read the cart and change it. No props pass through the layers in between.
tsx
// src/components/Header.tsx
import { useAppSelector } from '../hooks'
export function Header() {
const itemCount = useAppSelector((state) =>
state.cart.items.reduce((sum, i) => sum + i.quantity, 0), // (1)
)
return <header>My Shop · Cart: {itemCount}</header>
}tsx
// src/components/ProductCard.tsx
import { useAppDispatch } from '../hooks'
import { itemAdded } from '../features/cart/cartSlice'
type Product = { id: string; name: string; priceCents: number }
export function ProductCard({ product }: { product: Product }) {
const dispatch = useAppDispatch() // (2)
return (
<article>
<h2>{product.name}</h2>
<button
onClick={() =>
dispatch(itemAdded({ productId: product.id, name: product.name, priceCents: product.priceCents })) // (3)
}
>
Add to cart
</button>
</article>
)
}useAppSelectortakes a selector: a function from the whole state to the one value you want. The component subscribes to that value. When the value changes, and only then, the component draws again.useAppDispatch()returns thedispatchfunction.- On click, we create an action with
itemAdded(...)and give it todispatch. That is the whole story of changing the cart.
Header and ProductCard do not know each other. They do not share props. They only share the store. Click "Add to cart" on the Red mug and this happens:
text
dispatch → { type: 'cart/itemAdded', payload: { productId: 'p1', name: 'Red mug', priceCents: 1999 } }
reducer → the cart items become [{ productId: 'p1', ..., quantity: 1 }]
Header's selector now gives 1 instead of 0 → Header draws again → "Cart: 1"ProductCard did not draw again, because it did not select anything from the cart. That is the benefit over Context. Look at the picture of the difference.
8. Selectors: reading well
A selector is just a function from the state to a value. Because you will often need the same calculation in several places, write each one once, in a file next to the slice.
ts
// src/features/cart/cartSelectors.ts
import { createSelector } from '@reduxjs/toolkit'
import type { RootState } from '../../store'
export const selectCartItems = (state: RootState) => state.cart.items
export const selectItemCount = createSelector([selectCartItems], (items) =>
items.reduce((sum, i) => sum + i.quantity, 0),
)
export const selectCartTotalCents = createSelector([selectCartItems], (items) =>
items.reduce((sum, i) => sum + i.priceCents * i.quantity, 0),
)createSelector takes a list of input selectors and a function that calculates the result. It remembers the last answer. If the inputs are the same objects as last time, it returns the remembered answer without recalculating. We checked this: calling the selector twice on the same state calculated once. For a simple sum this does not matter. For a heavy calculation, such as filtering and sorting ten thousand rows, it matters a lot.
A component then writes const total = useAppSelector(selectCartTotalCents). Nothing else.
The mistake that makes a component redraw forever
tsx
// Wrong: this makes a NEW object on every call
const summary = useAppSelector((s) => ({ count: s.cart.items.length }))React-Redux compares the selector's result with the last result using ===. A new object is never === an old one, so it always looks "changed". React-Redux warns you in development: "Selector unknown returned a different result when called with the same parameters. This can lead to unnecessary rerenders." We saw exactly this warning.
Fix it by selecting the simple values separately (const count = useAppSelector(s => s.cart.items.length)), or by building the object with createSelector, which returns the same object while its inputs stay the same.
9. The reducer rules
A reducer must be a pure function. That means the output depends only on the inputs, and nothing else in the world is touched. In practice:
| A reducer must not | Because |
|---|---|
call fetch or any network request | the answer takes time, and a reducer must finish immediately |
use Date.now() or Math.random() | calling it again with the same action would give a different result |
| change anything outside itself | the action log could no longer be replayed |
If you need a time or a random id, create it before you dispatch, and put it in the action's payload. Then the reducer receives the same input and always gives the same output.
Also, only put plain data in the state and in actions: numbers, strings, booleans, arrays and plain objects. Not a Date, a Map, a class instance or a function. Redux wants to be able to save and replay everything as JSON. When we dispatched an action with a Date, RTK printed: "A non-serializable value was detected in an action, in the path: payload." The fix is to store the date as text (date.toISOString()) or as a number of milliseconds.
10. Work that takes time: createAsyncThunk
Reducers cannot call a server. So where does the code that loads the products go?
The answer is a thunk. A thunk is a function that you dispatch like an action, but which runs your own code, such as a network call, and then dispatches real actions about what happened. RTK makes them with createAsyncThunk.
ts
// src/features/products/productsSlice.ts
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
export type Product = { id: string; name: string; priceCents: number }
export const loadProducts = createAsyncThunk('products/load', async () => { // (1)
const res = await fetch('/api/products')
if (!res.ok) throw new Error(`The server answered ${res.status}`)
return (await res.json()) as Product[] // (2)
})
type ProductsState = {
status: 'idle' | 'loading' | 'succeeded' | 'failed'
items: Product[]
error: string | null
}
const initialState: ProductsState = { status: 'idle', items: [], error: null }
const productsSlice = createSlice({
name: 'products',
initialState,
reducers: {},
extraReducers: (builder) => { // (3)
builder
.addCase(loadProducts.pending, (state) => {
state.status = 'loading'
state.error = null
})
.addCase(loadProducts.fulfilled, (state, action) => {
state.status = 'succeeded'
state.items = action.payload // (4)
})
.addCase(loadProducts.rejected, (state, action) => {
state.status = 'failed'
state.error = action.error.message ?? 'Something went wrong'
})
},
})
export default productsSlice.reducercreateAsyncThunktakes a name ('products/load') and anasyncfunction. That function is your own code. It can do anything, includingawait fetch(...).- Whatever the function returns becomes the payload of the success action. If it throws, the failure action is used.
extraReducerslets this slice react to actions it did not create itself. Thebuilderadds one case for each action to listen to.- In the success case,
action.payloadis the value returned at (2).
The thunk automatically dispatches three actions, named after the thunk's name. We recorded them in the order they appear:
text
products/load/pending → status becomes 'loading'
products/load/fulfilled → status becomes 'succeeded', the products are stored
(or) products/load/rejected → status becomes 'failed', the message is storedThis is exactly the three-situation idea from page 6.4.3 (loading, success, error), now written as a Redux slice. In a component you start it once when the page opens:
tsx
// src/components/ProductListPage.tsx
import { useEffect } from 'react'
import { useAppDispatch, useAppSelector } from '../hooks'
import { loadProducts } from '../features/products/productsSlice'
export function ProductListPage() {
const dispatch = useAppDispatch()
const status = useAppSelector((s) => s.products.status)
const products = useAppSelector((s) => s.products.items)
const error = useAppSelector((s) => s.products.error)
useEffect(() => {
if (status === 'idle') dispatch(loadProducts()) // (1)
}, [status, dispatch])
if (status === 'loading' || status === 'idle') return <p>Loading…</p>
if (status === 'failed') return <p role="alert">Could not load: {error}</p>
return (
<ul>
{products.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
)
}- We only start loading when the status is
'idle', so the products are not fetched again every time the component appears.
For this to work, the new slice must be added to the store. This is the same file as before, with one more line:
ts
// src/store.ts
import { configureStore } from '@reduxjs/toolkit'
import cartReducer from './features/cart/cartSlice'
import productsReducer from './features/products/productsSlice'
export const store = configureStore({
reducer: {
cart: cartReducer,
products: productsReducer, // (1)
},
})
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch- The new key. The state is now
{ cart: ..., products: ... }, andRootStateupdates by itself.
Honest advice about this
Look at how much code it took to load a list: a thunk, three cases, four fields of state, an effect, and a status check. And it still has none of the things listed at the end of page 6.4.3: no cache that refreshes quietly, no sharing between two screens, no automatic retry.
This is why current projects do not keep server data in Redux. They keep it in TanStack Query (pages 6.4.10 and 6.4.11) and use Redux only for client state: things that exist only in the browser, like a cart that has not been ordered yet, the open or closed sidebar, or the theme. (Redux Toolkit also ships its own server-data tool called RTK Query. Teams that already use Redux often pick it. TanStack Query is more common overall, and it is what this book teaches.) You still need to know createAsyncThunk, because large existing codebases are full of it and interviewers ask about it.
11. Tools and habits
- Redux DevTools is a free browser extension.
configureStorealready connects to it. It shows the list of every action, the state before and after each one, and lets you jump back to any earlier moment. This is the "describable and replayable" benefit from the start of the page, and it is the best reason to use Redux. - Folder by feature. Keep each feature's slice, selectors and components near each other (
features/cart/,features/products/), not all slices in one folder and all components in another. - Keep the state small and flat. Store ids and look the rest up, rather than copying the same product object into five places.
- Middleware is code that sits between
dispatchand the reducer, and can log, delay or transform actions. Thunks are one kind.configureStoreincludes the ones you need, and you rarely write your own.
What the interviewer will push on
"Explain Redux's data flow." Say it as the loop: a component dispatches an action, the store runs it through the reducer, the reducer returns new state, and subscribed components re-render if their selected value changed. Mention "one-way". The interviewer checks that you know the components never change state directly.
"Why must reducers be pure, and what does that give you?" Same input, same output, no side effects. It makes every change predictable, loggable and replayable (time travel, bug reports). The wrong answer is "because the docs say so".
"You wrote state.items.push(...) in a reducer. Is that mutation?" It looks like it, but Redux Toolkit runs it through Immer, which records the changes on a draft and produces a new immutable state. Then add the catch: you must either change the draft or return a new value, never both, and it only works inside createSlice.
"How do you handle async work in Redux?" createAsyncThunk: it dispatches pending, fulfilled and rejected actions, and extraReducers handles each. Then add: for server data, TanStack Query or RTK Query is better, because caching and retries are built in.
"Redux, Context or Zustand?" Context for rarely changing values (theme, current user). A store with selectors when many components read frequently changing data. Redux when you want the strict structure and DevTools for a large team. Server data in neither: in a data-fetching cache.
"Why does my component re-render too often?" Usually a selector that returns a new object or array every time. Select primitives, or memoise with createSelector.
One thing to volunteer: say that you keep non-serializable values out of the store and that you put ids and timestamps into the action payload instead of calling Date.now() in the reducer. It shows you understand why the rules exist.
Recall
- Three parts: state (one tree in the store), action (a plain object saying what happened:
{ type, payload }), reducer (a pure function(oldState, action) => newState). Components dispatch actions and select values. Nothing else changes the state. - Install
@reduxjs/toolkit(store and tools) andreact-redux(Provider, hooks). createSlice({ name, initialState, reducers })writes the reducer and the action creators. The action type is'name/reducerName'.- Immer: inside
createSliceyou may writestate.items.push(x). It changes a draft, and Immer produces a new immutable state. Change the draft or return a value, never both. configureStore({ reducer: { cart: cartReducer } }); exportRootStateandAppDispatch; make typed hooks withuseDispatch.withTypes<AppDispatch>()anduseSelector.withTypes<RootState>(). Wrap the app in<Provider store={store}>.- Selectors:
useAppSelector(s => s.cart.items). A component redraws only when its selected value changes (compared with===). A selector that returns a new object each time causes needless redraws. UsecreateSelectorto cache calculated values. - Reducers must be pure: no fetch, no
Date.now(), no random. Only serializable data in state and actions. createAsyncThunkruns your async code and dispatchespending,fulfilled,rejected, handled inextraReducers. For server data, prefer TanStack Query. Use Redux for client state.- Redux DevTools shows every action and lets you time travel.
Self-test: Name the three parts of Redux and what each does. · Why is existing.quantity += 1 allowed in a reducer? · What does createSlice generate for you? · Why does s => ({ count: s.cart.items.length }) cause problems? · What are the three actions a thunk dispatches?
Next: 6.4.8 teaches the two lighter options, Zustand and Context, with the same cart, so you can compare all three on the same problem and choose with confidence.