Skip to content

Volume ITechnology

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 bankIn ReduxWhat it is
The ledgerState (kept in the store)One object that holds the data of the whole app
The slipActionA plain object that says what happened
The teller with the rule bookReducerA 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.

Componentbutton onClick callsdispatch(itemAdded(mug))Action{ type: 'cart/itemAdded', payload: { mug } }Reducer(oldState, action)=> newStateStoreholds the one statetree for the whole appSelectorstate.cart.items.lengthpicks one valueComponent draws againonly if the selectedvalue changed①②③ new state④⑤Only the reducer may change state.Everyone else asks by dispatching an action.
The whole of Redux in one picture. A button dispatches an action (a plain object that says what happened). The reducer works out the next state. Components that select that part of the state draw again. Nothing else is allowed to change the state.

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-redux

Two 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.

  1. initialState is what the cart looks like when the app starts: an empty list.
  2. 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.
  3. Each function under reducers is one kind of change. It receives the current state and an action. 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 the quantity field".
  4. Look closely. This line changes existing.quantity directly, which on page 6.4.2 we said you must never do. In Redux Toolkit it is allowed. The next section explains why.
  5. A reducer can instead return a whole new state. Here it throws everything away and returns to the start.
  6. createSlice writes 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.
  7. 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)
  1. The keys of reducer become the keys of the state. The whole state is now { cart: { items: [...] } }. When you add a products slice later, it becomes another key here. configureStore also turns on helpful checks in development, such as a warning if you put a value that cannot be saved as JSON into the state.
  2. RootState is the TypeScript type of the whole state. It is worked out from the store, so it can never disagree with it.
  3. AppDispatch is the type of the dispatch function. 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>
  )
}
  1. useAppSelector takes 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.
  2. useAppDispatch() returns the dispatch function.
  3. On click, we create an action with itemAdded(...) and give it to dispatch. 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.

Context: one value for everyoneProvidervalue = { theme, cart }Headerreads cartChartreads themeBadgereads cartCart changed: all three draw again.The chart did not need to.Selectors: each reads its own pieceStore{ theme, cart }Headerselects cartChartselects themeBadgeselects cartCart changed: only Header and Badge draw again.The chart stays still.Same change, very different amount of work
Left: context re-renders every component that reads it, whatever part it cares about. Right: a selector store re-renders only the components whose selected value changed. Red outline means "draws again".

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 notBecause
call fetch or any network requestthe 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 itselfthe 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.reducer
  1. createAsyncThunk takes a name ('products/load') and an async function. That function is your own code. It can do anything, including await fetch(...).
  2. Whatever the function returns becomes the payload of the success action. If it throws, the failure action is used.
  3. extraReducers lets this slice react to actions it did not create itself. The builder adds one case for each action to listen to.
  4. In the success case, action.payload is 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 stored

This 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>
  )
}
  1. 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
  1. The new key. The state is now { cart: ..., products: ... }, and RootState updates 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. configureStore already 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 dispatch and the reducer, and can log, delay or transform actions. Thunks are one kind. configureStore includes 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) and react-redux (Provider, hooks).
  • createSlice({ name, initialState, reducers }) writes the reducer and the action creators. The action type is 'name/reducerName'.
  • Immer: inside createSlice you may write state.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 } }); export RootState and AppDispatch; make typed hooks with useDispatch.withTypes<AppDispatch>() and useSelector.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. Use createSelector to cache calculated values.
  • Reducers must be pure: no fetch, no Date.now(), no random. Only serializable data in state and actions.
  • createAsyncThunk runs your async code and dispatches pending, fulfilled, rejected, handled in extraReducers. 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.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet