Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 132 ยท Context and Shared State

Redux Toolkit and Zustand Walkthrough

A hands-on walkthrough of Redux Toolkit and Zustand - slices, stores, memoized selectors, thunks, middleware and re-render control - with runnable stand-ins and an honest trade-off comparison.

The state management overview introduced Redux, Zustand, Jotai and signals in a few lines each. This lesson goes one level deeper into the two most widely used options for client state: Redux Toolkit and Zustand. You will build a small app with each, so you can feel the difference in structure, see how selectors control re-renders, and make a decision based on trade-offs instead of hype.

Both tools share one idea that you already met in external stores: the state lives outside React, components subscribe to the part they need through useSyncExternalStore, and updates go through a function that notifies subscribers. Everything else, from actions and reducers to middleware, is about how much structure you want around that core.

@reduxjs/toolkit, react-redux and zustand are npm packages that our editor cannot load. Real-library code here is read-only (Redux Toolkit 2, React-Redux 9 and Zustand 5 style). The runnable examples use short hand-written stand-ins with the same API shapes, so you can watch the data flow in the console. Real libraries add many details (Immer, DevTools, middleware, TypeScript support), so install them in your own project to use them.

Redux Toolkit: the data flow

Redux has one rule that explains the rest: state is read-only and changes only through dispatched actions. A component never edits the store. It describes what happened (todos/added), a pure reducer computes the next state, and subscribers re-run their selectors.

flowchart LR
    UI["Component"] -->|"dispatch(action)"| S["Store"]
    S -->|"state, action"| R["Reducers"]
    R -->|"next state"| S
    S -->|"notify"| SEL["useSelector<br/>re-runs selectors"]
    SEL -->|"value changed?"| UI

Redux's one-way data flow. The store is the only place where state changes, and a selector decides whether a component renders again.

In Redux Toolkit (RTK), the standard way to write Redux, you write one slice per feature. A slice bundles a name, initial state and reducers; RTK generates the action creators and the action type strings (name/reducerName). Inside reducers you may write code that looks like mutation, because RTK runs it on an Immer draft and turns it into an immutable update. The real shape is:

JSX
// features/todos/todosSlice.js (needs @reduxjs/toolkit)
import { createSlice } from '@reduxjs/toolkit';

const todosSlice = createSlice({
  name: 'todos',
  initialState: { items: [], filter: 'all', nextId: 1 },
  reducers: {
    added(state, action) {
      state.items.push({ id: state.nextId++, title: action.payload, done: false });
    },
    toggled(state, action) {
      const todo = state.items.find((item) => item.id === action.payload);
      if (todo) todo.done = !todo.done;
    },
    filterChanged(state, action) {
      state.filter = action.payload;
    },
  },
});

export const { added, toggled, filterChanged } = todosSlice.actions;
export default todosSlice.reducer;
JSX
// app/store.js
import { configureStore } from '@reduxjs/toolkit';
import todos from '../features/todos/todosSlice';
import ui from '../features/ui/uiSlice';

export const store = configureStore({ reducer: { todos, ui } });
JSX
// main.jsx
import { Provider } from 'react-redux';
createRoot(document.getElementById('root')).render(
  <Provider store={store}>
    <App />
  </Provider>
);

configureStore also adds the thunk middleware (for async logic), the Redux DevTools connection and development checks that warn when you mutate state outside a reducer or put non-serializable values in the store. Two habits keep Redux code tidy: name actions as events that happened (todos/added, not todos/setItems) and keep reducers pure (no fetches, no random values, no dates; put those in the action or in a thunk).

Selectors decide who re-renders

useSelector(selector) subscribes a component to the result of the selector. After every dispatch, React-Redux runs the selector again and re-renders the component only if the result is a different value (compared with ===). That makes the shape of selectors important:

  • state => state.todos.items.length returns a number; equal numbers do not re-render.
  • state => state.todos.items.filter(...) returns a new array every time, so it always looks changed. It re-renders on every dispatch, and React-Redux warns about it in development.
  • The fix is a memoized selector created with createSelector (from the Reselect library, re-exported by RTK). It recomputes only when its inputs change by reference, and otherwise returns the same array.
flowchart TD
    A["dispatch(action)"] --> B["Input selectors run:<br/>items, filter"]
    B --> C{"Same references<br/>as last time?"}
    C -->|"yes"| D["Return the cached result"]
    C -->|"no"| E["Run the combiner,<br/>cache the new result"]

A memoized selector compares its inputs by reference. Unrelated actions leave them untouched, so the expensive work is skipped.

A runnable Redux-style app

This stand-in has createSlice (using structuredClone where RTK uses Immer), configureStore with two slices, a createSelector and the useSelector hook. It logs every action and every time the visible-todos selector actually recomputes. Add a todo, toggle one, change the filter, and press the "unrelated" button.

A hand-written mini Redux Toolkit app

The console starts with one selector: visible todos recomputed. Add a todo, toggle one, or change the filter, and each action: line is followed by a recompute, because items or filter changed. Now press the unrelated button: you see action: ui/clicked and no recompute. The ui slice produced new state, but state.todos kept the same reference, so the memoized selector returned its cached array. That is the whole performance story of Redux: unrelated state changes cost almost nothing as long as slices that did not change keep their identity.

In real code, selectors that you use in many places live next to their slice (selectVisibleTodos), so components do not depend on the state's shape. For lists of entities, RTK also offers createEntityAdapter, which stores items as an ids array plus an entities lookup and generates ready-made selectors.

Async work and server data

Reducers must be pure, so asynchronous work lives in thunks: functions you dispatch that can do anything and then dispatch plain actions. RTK's createAsyncThunk generates the pending, fulfilled and rejected actions for you.

JSX
const loadTodos = createAsyncThunk('todos/loaded', async () => {
  const response = await fetch('/api/todos');
  if (!response.ok) throw new Error('Request failed');
  return response.json();
});

// in createSlice(...)
extraReducers: (builder) => {
  builder
    .addCase(loadTodos.pending, (state) => { state.status = 'loading'; })
    .addCase(loadTodos.fulfilled, (state, action) => { state.status = 'ready'; state.items = action.payload; })
    .addCase(loadTodos.rejected, (state) => { state.status = 'failed'; });
},

This works, but you are now writing loading flags and caching by hand, which is the problem described in server state versus client state. Redux Toolkit ships RTK Query for exactly this (a data layer with cache and invalidation), and many teams use TanStack Query instead. Either way, keep the Redux store for state the browser owns.

createAction and createReducer: the pieces under createSlice

createSlice is built from two smaller helpers that you can also use alone, and you will meet them in older Redux Toolkit code.

createAction makes an action creator from a type string. Calling it returns { type, payload }, and the creator's toString() gives the type, so it can be used as a key:

JavaScript
// Read-only: needs @reduxjs/toolkit
import { createAction, createReducer } from '@reduxjs/toolkit';

const added = createAction('todos/added');   // added('Buy milk') -> { type: 'todos/added', payload: 'Buy milk' }
const toggled = createAction('todos/toggled');
const cleared = createAction('todos/cleared');

const todosReducer = createReducer({ items: [] }, (builder) => {
  builder
    .addCase(added, (state, action) => {
      state.items.push({ id: Date.now(), text: action.payload, done: false });
    })
    .addCase(toggled, (state, action) => {
      const todo = state.items.find((t) => t.id === action.payload);
      if (todo) todo.done = !todo.done;
    })
    .addCase(cleared, (state) => {
      state.items = [];
    })
    .addMatcher((action) => action.type.endsWith('/rejected'), (state) => {
      state.error = true;
    });
});

createReducer takes the initial state and a builder callback. addCase handles one action, addMatcher handles every action that passes a test function (here, any rejected thunk), and addDefaultCase is the fallback. Like createSlice, it runs your code on an Immer draft, which is why push and assignment are safe. The builder form is the one current Redux Toolkit versions support (the old object-map notation was removed).

Use createSlice by default: it generates the action creators for you. Reach for createAction and createReducer when several reducers must react to one action (for example a logout action that every slice resets on), because a slice's own actions belong to that slice, while a shared action creator can be imported by many.

Why Toolkit instead of hand-written Redux

Task Classic Redux Redux Toolkit
Update nested state Spread every level by hand Write "mutating" code on an Immer draft
Action types and creators Constants and functions by hand Generated by createSlice / createAction
Store setup createStore, combineReducers, middleware wiring configureStore with sensible defaults
Async logic A thunk middleware you add yourself createAsyncThunk included; thunk is on by default
Mistakes Silent Dev checks for mutation outside reducers and non-serializable values

Zustand: a store that is also a hook

Zustand takes the same core and removes the ceremony. There is no provider, no action types and no reducers (you can still use a reducer if you want). You call create with a function that receives set and get and returns your state and the functions that change it, in one object. What you get back is a hook.

JSX
// needs the zustand package
import { create } from 'zustand';

export const useCartStore = create((set, get) => ({
  items: [],
  addItem: (product) =>
    set((state) => ({ items: [...state.items, product] })),
  clear: () => set({ items: [] }),
  total: () => get().items.reduce((sum, item) => sum + item.price, 0),
}));

function CartBadge() {
  const count = useCartStore((state) => state.items.length);
  return <span>{count}</span>;
}

set shallow-merges the object you give it into the state (immutable updates are still your job, though the immer middleware can help). The store also works outside React: useCartStore.getState() reads it and useCartStore.setState(...) writes it, which is handy for event listeners, tests and non-component code.

Selectors and re-renders

The rule from Redux applies: a component re-renders when its selector's result changes by Object.is. Selecting a primitive or an existing reference (such as a function from the store) is cheap. Selecting a new object or array on every call is the classic bug: in Zustand 5 it causes an infinite render loop, and you must wrap the selector with useShallow so that equal contents count as equal:

JSX
import { useShallow } from 'zustand/react/shallow';

const { items, clear } = useCartStore(
  useShallow((state) => ({ items: state.items, clear: state.clear }))
);

Now a runnable stand-in for the store, including a middleware. In Zustand a middleware is a function that wraps your state creator and can intercept set. The logger below prints the state before and after each change; real middleware such as devtools (Redux DevTools), persist (saving to storage) and immer use the same shape and are composed by nesting: create(devtools(persist(creator, options))).

A hand-written mini Zustand store with middleware

On load you see one render line for each of the four components. Press "Add Tea": the logger prints before: [] and after: ["Tea x1"], then only CartList rendered and CartTotal rendered appear. The AddButton components do not re-render, because each selected only the addItem function, which never changes. Press "Add Tea" again and the quantity of the existing line becomes 2, which CartTotal reflects. Each component is subscribed to exactly the slice of state it uses.

For larger Zustand apps, the slices pattern splits one store into several creator functions (createCartSlice, createUserSlice) that are spread into a single create call. It gives you Redux-like modularity without actions and reducers.

Redux Toolkit or Zustand?

Both are good. The honest differences are about structure and scale:

Redux Toolkit Zustand
Boilerplate Moderate: slices, store, provider Very little: one create call
Structure Enforced: actions, reducers, selectors Up to you (slices pattern helps)
Debugging Excellent: every action logged, time travel Good with the devtools middleware
Updates Through actions, one place Any code can call set, even outside React
Async data Thunks, RTK Query Plain async functions in the store
Learning curve Steeper, many concepts Gentle
Best for Large teams, complex update logic, audit trail Small to medium apps, local feature state

A simple way to choose:

flowchart TD
    Q1{"Is the data from a server?"} -->|"yes"| A1["Use a server-state tool first:<br/>TanStack Query, RTK Query, SWR"]
    Q1 -->|"no, browser-only"| Q2{"Used by one component<br/>or a small subtree?"}
    Q2 -->|"yes"| A2["useState, useReducer, context"]
    Q2 -->|"no, many distant components"| Q3{"Big team, complex flows,<br/>need strict structure?"}
    Q3 -->|"yes"| A3["Redux Toolkit"]
    Q3 -->|"no"| A4["Zustand (or Jotai)"]

Start with the simplest tool that fits the kind of state you have. Most apps never need the bottom two boxes for more than a few values.

Two more points. First, migrating is cheap early and costly late, but both tools keep components decoupled: components read through selectors and call functions, so swapping the store behind them is manageable. Second, neither library replaces thinking about where state should live. Put state as close as possible to where it is used (choosing a state structure, lifting state up) and promote it to a global store only when distant components truly share it. If you are unsure, start with context and a reducer, and reach for a store when re-renders or boilerplate begin to hurt.

Common mistakes

  • Putting everything in the store, including form drafts, open/closed flags of one dialog and server responses. Most of it belongs in components or a server-state library.
  • Selecting too much: useSelector((state) => state) or useStore() with no selector subscribes the component to every change.
  • Creating new objects in selectors without memoization (createSelector) or useShallow.
  • Mutating state outside a reducer in Redux, or mutating the existing object in a Zustand set function. Always produce new objects and arrays, except inside RTK reducers where Immer allows draft mutation.
  • Non-serializable values (class instances, functions, promises) in a Redux store, which breaks DevTools and persistence.
  • Dispatching in render. Dispatch from event handlers and effects, never in the component body.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can Redux Toolkit reducers contain code that looks like mutation (state.value += 1)?

    createSlice wraps the reducer with Immer. You change a draft, and RTK produces a new immutable state with structural sharing.
  2. 2. useSelector(state => state.todos.items.filter(t => t.done)) makes the component re-render after every dispatch. Why?

    Components re-render when the selector's result is a different value (===). A fresh array each time always looks new. Use createSelector to return a cached array.
  3. 3. What does a memoized selector from createSelector do when an unrelated slice changes?

    createSelector compares the outputs of its input selectors by reference. If none changed, it skips the combiner and returns the previous result.
  4. 4. Which Zustand feature wraps a store creator to log or persist changes?

    Middleware are functions that take your state creator and return a new one, intercepting set. They are nested around the creator.
  5. 5. A Zustand component selects state => ({ a: state.a, b: state.b }) and loops forever in Zustand 5. What is the fix?

    The selector creates a new object on every call. useShallow compares the properties instead of the object identity, and separate selectors return values that are already stable.

Summary

  • Redux Toolkit organizes state into slices with generated actions. Reducers stay pure (Immer lets you write mutating-looking code), configureStore sets up the store and DevTools, and thunks or RTK Query handle async work.
  • Components subscribe with selectors and re-render only when the selected value changes by reference. Use createSelector to memoize derived data.
  • Zustand is a store you create with create and use as a hook: state and actions in one object, no provider, readable outside React, extensible with middleware (devtools, persist, immer).
  • Select the smallest piece of state a component needs; use useShallow when you must return an object or array.
  • Choose by need: server data goes to a server-state library, local state stays in components or context, and for shared browser state pick Redux Toolkit for strict structure at scale and Zustand for a light touch.

Next: Form Validation