The last chapter built a store from three functions and connected it to React with useSyncExternalStore and selectors. Redux is that store with one strong opinion added: state never changes directly. Every change is described as a plain object called an action, and a pure function called a reducer computes the next state from the current state and the action.
That one rule costs you some ceremony and buys you a lot: a log of everything that ever happened, state you can rewind, middleware that sees every change, and reducers you can test without React. This chapter covers the idea Redux came from, the modern way to write it (Redux Toolkit 2 with react-redux 9, the versions in the sandbox), and the honest answer to "should I still use Redux in 2026?"
The problem: who changed this?#
In the toy store, any code anywhere can call store.setState(...). In a small app that's freedom. In a large one, with dozens of developers, it becomes the question every debugging session starts with: the cart total is wrong; what changed it, and when? With setState calls scattered across components, effects, socket handlers and helpers, there's no single place to look.
Facebook described this problem in 2014 with a chat unread-message count that kept going wrong, and its answer was an architecture called Flux: data flows in one direction. Views don't change state; they dispatch actions, plain descriptions of what happened ({ type: "message/received", payload }). Stores receive every action and decide how state changes. Views re-render from the stores. Because every change enters through one door, you can log, replay and reason about all of them.
Redux (2015, Dan Abramov and Andrew Clark) simplified Flux into three principles:
- A single store: the whole app's client state is one object tree.
- State is read-only: the only way to change it is to dispatch an action.
- Changes are made by pure reducers:
(state, action) => newState, with no side effects, no mutation of the input, and the same output for the same input.
Build it: Redux is the toy with a reducer#
You can turn last chapter's store into Redux by replacing setState with dispatch, which runs the reducer:
type Action = { type: string; payload?: any };
type Reducer<S> = (state: S, action: Action) => S;
function createReduxStore<S>(reducer: Reducer<S>, initial: S) {
let state = initial;
const listeners = new Set<() => void>();
return {
getState: () => state,
dispatch(action: Action) {
state = reducer(state, action); // the only way state changes
listeners.forEach((l) => l());
return action;
},
subscribe(l: () => void) {
listeners.add(l);
return () => {
listeners.delete(l);
};
},
};
}
type State = { books: { id: number; title: string; read: boolean }[] };
function booksReducer(state: State, action: Action): State {
switch (action.type) {
case "books/added":
return { books: [...state.books, { id: action.payload.id, title: action.payload.title, read: false }] };
case "books/toggled":
return { books: state.books.map((b) => (b.id === action.payload ? { ...b, read: !b.read } : b)) };
default:
return state; // unknown actions leave state untouched
}
}
const store = createReduxStore(booksReducer, { books: [] });
const history: { action: Action; state: State }[] = [];
store.subscribe(() => console.log("state:", JSON.stringify(store.getState())));
for (const action of [
{ type: "books/added", payload: { id: 1, title: "Refactoring" } },
{ type: "books/added", payload: { id: 2, title: "SICP" } },
{ type: "books/toggled", payload: 1 },
]) {
store.dispatch(action);
history.push({ action, state: store.getState() });
}
// Because the reducer is pure, the action log alone can rebuild any past state.
const replayed = history.slice(0, 2).reduce((s, h) => booksReducer(s, h.action), { books: [] } as State);
console.log("state after 2 actions, replayed:", JSON.stringify(replayed));Look at the last two lines. Because the reducer is pure and actions are plain data, the action log is enough to reconstruct any past state: start from the initial state and fold the actions back through the reducer. That's the trick behind Redux DevTools' time travel, and it falls straight out of the three principles. It also means you can serialize the log, attach it to a bug report and replay the user's session.
The cost is visible too: a switch, hand-written immutable updates with spreads, string action types you can typo, and (not shown) action creator functions for each type. Classic Redux code was famous for this boilerplate. Redux Toolkit exists to remove it.
Redux Toolkit: the modern way to write Redux#
Redux Toolkit (RTK) is the official, recommended way to write Redux; the Redux docs teach it as the standard and treat hand-written reducers, action types and createStore as legacy patterns. Version 2 shipped in December 2023 with Redux core 5 and react-redux 9. Its core APIs:
configureStore: creates the store with good defaults (thunk middleware, development checks, DevTools).createSlice: one call generates a slice reducer, its action creators and its action types.createAsyncThunk: async logic that dispatches pending, fulfilled and rejected actions.createSelector(from Reselect): memoized selectors.createApi(RTK Query): a server-cache layer, covered briefly below and in depth in chapter 39.
Here's the reading list as a Redux Toolkit app. Books load through a thunk, and a separate ui slice holds the theme.
import { useEffect } from "react";
import { Provider, useDispatch, useSelector } from "react-redux";
import { Rendered } from "guide-tools";
import { fetchBooks, flipTheme, selectUnreadCount, store, toggleRead, type AppDispatch, type RootState } from "./store";
// Typed hooks, defined once for the app.
const useAppDispatch = useDispatch.withTypes<AppDispatch>();
const useAppSelector = useSelector.withTypes<RootState>();
function UnreadBadge() {
const unread = useAppSelector(selectUnreadCount);
return <Rendered label="UnreadBadge">Unread: {unread}</Rendered>;
}
function ThemeLabel() {
const theme = useAppSelector((s) => s.ui.theme);
return <Rendered label="ThemeLabel">Theme: {theme}</Rendered>;
}
function BookList() {
const dispatch = useAppDispatch();
const items = useAppSelector((s) => s.books.items);
const status = useAppSelector((s) => s.books.status);
useEffect(() => {
if (status === "idle") dispatch(fetchBooks());
}, [status, dispatch]);
if (status === "loading" || status === "idle") return <p>Loading books...</p>;
return (
<Rendered label="BookList">
{items.map((b) => (
<label key={b.id} style={{ display: "block" }}>
<input type="checkbox" checked={b.read} onChange={() => dispatch(toggleRead(b.id))} /> {b.title}
</label>
))}
</Rendered>
);
}
export default function App() {
return (
<Provider store={store}>
<UnreadBadge />
<ThemeLabel />
<BookList />
<button onClick={() => store.dispatch(flipTheme())}>Flip theme</button>
</Provider>
);
}Toggle a book: UnreadBadge and BookList re-render, ThemeLabel doesn't. Flip the theme: only ThemeLabel. Same selective behavior as the toy, for the same reason. Open the console to see what toggleRead(3) returns: a plain action object, { type: "books/toggleRead", payload: 3 }, with the type built from the slice name and the reducer key.
Redux is a one-way loop. Every change takes the same path, so you can always answer: what happened, and what did it do to the state?
Mapping it back to the toy#
| Toy store | Redux Toolkit |
|---|---|
createStore(initial) | configureStore({ reducer }); initial state comes from each slice |
setState(partial) | dispatch(action), and the reducer decides what changes |
subscribe(listener) | store.subscribe(listener), used by <Provider> |
useStore(store, selector) | useSelector(selector), built on useSyncExternalStoreWithSelector |
| Context holding the store | <Provider store={store}> (the store reference never changes, so it causes no re-renders) |
shallow / equality cache | useSelector(selector, shallowEqual) or a memoized createSelector |
useSelector reads the store from context and calls useSyncExternalStoreWithSelector (from the React team's use-sync-external-store package) with your selector and an optional equality function. Like the toy, it re-renders only when the selected value changes, compared with === by default. Unlike the toy, it also remembers the last state it saw and skips running the selector when the store state is the same object, which is why an unstable selector costs re-renders here rather than an infinite loop.
createSlice and Immer#
The reducer in toggleRead looks like it mutates: book.read = !book.read. It doesn't. createSlice runs every case reducer through Immer: your function receives a draft, a proxy that records every change you make, and Immer then produces a new immutable state, copying only the objects along the path you changed and sharing everything else. Unchanged books keep their references, which is exactly what selectors need.
Two Immer rules to know cold:
- Either mutate the draft or return a new value, not both.
state.items.push(x); return state.itemsthrows. Returning a brand new state (return initialState) is fine when you don't touch the draft. - Drafts only exist inside the reducer. Code outside, like a component, still has to treat state as immutable, and in development RTK's immutability middleware throws if something mutates the store state outside a reducer.
configureStore's defaults#
configureStore sets up, with no options:
- the thunk middleware, so you can dispatch functions for async logic;
- in development, the immutability check (throws when state is mutated outside reducers) and the serializability check (warns when you put class instances, promises or functions into state or actions, which would break DevTools and persistence);
- the Redux DevTools connection, if the browser extension is installed.
You customize middleware with a callback that receives the defaults: middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger). In RTK 2 the callback form is required; the old array form was removed so you can't accidentally drop the defaults.
Async: thunks and createAsyncThunk#
Reducers must be pure, so where does async code go? Into middleware. A thunk is a function you dispatch instead of an object: the thunk middleware intercepts it and calls it with dispatch and getState, so it can await things and dispatch real actions as it goes.
createAsyncThunk("books/fetch", payloadCreator) packages the common case: it returns a thunk that dispatches books/fetch/pending, runs your async function, then dispatches books/fetch/fulfilled with the result or books/fetch/rejected with the error. Your slice handles those in extraReducers, the place for actions the slice didn't define itself.
Notice what that sandbox is doing, though: copying server data into a client store, with hand-written status and error fields, and no caching, deduplication or refetching. That's precisely the misplacement kinds of state warned about. Thunks are still the right tool for async workflows (a checkout that calls three endpoints and dispatches progress), but for plain data fetching use RTK Query, which follows.
Middleware: a pipeline around dispatch#
Middleware has a curried signature that looks strange until you see what each layer is for:
const logger: Middleware = (storeApi) => (next) => (action) => {
console.log("dispatching", action);
const result = next(action); // pass it on: next middleware, or the reducer
console.log("next state", storeApi.getState());
return result;
};storeApi gives getState and dispatch. next is the next middleware in the chain (the last one's next is the real reducer step). Each middleware can inspect the action, change it, swallow it, call next more than once, or dispatch something else. Thunks, logging, analytics, crash reporting and RTK Query's cache lifecycle are all middleware.
import { configureStore, createSlice, type Middleware } from "@reduxjs/toolkit";
const counter = createSlice({
name: "counter",
initialState: { value: 0 },
reducers: {
incremented(state) {
state.value += 1;
},
},
});
const logger: Middleware = (storeApi) => (next) => (action) => {
console.log("1. logger sees", action);
const result = next(action);
console.log("3. state is now", storeApi.getState());
return result;
};
const store = configureStore({
reducer: { counter: counter.reducer },
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),
});
store.subscribe(() => console.log("2. subscribers notified"));
store.dispatch(counter.actions.incremented());
// A thunk: the thunk middleware calls it instead of passing it to reducers.
store.dispatch((dispatch, getState) => {
console.log("thunk running, value =", getState().counter.value);
dispatch(counter.actions.incremented());
});The numbered logs show the order: middleware sees the action first, the reducer runs inside next, subscribers are notified, and control returns to the middleware after next. The thunk itself never reaches the logger as an action, because the thunk middleware sits earlier in the chain and intercepts it; the incremented action it dispatches does.
For reacting to actions with side effects ("when order/placed happens, show a toast and refetch the cart"), RTK provides createListenerMiddleware, a lighter alternative to the redux-saga and redux-observable libraries that older codebases use.
Selectors and createSelector#
A selector is a function from root state to some value. Two reasons to name and reuse them rather than writing inline arrows everywhere: they encapsulate the state shape (components don't need to know state.books.items), and they're where derived data is computed, which, as kinds of state argued, is where derived data belongs.
Derived data brings back the stability problem from the last chapter. This selector returns a new array on every call:
const selectUnread = (state: RootState) => state.books.items.filter((b) => !b.read);With useSelector, that doesn't loop (react-redux caches the result per store state), but it does mean a re-render on every dispatched action, even ones that don't touch books, because each new state produces a new array that isn't === the last. In development react-redux even warns you: the selector "returned a different result when called with the same parameters".
createSelector fixes this by memoizing on inputs:
import { createSelector } from "@reduxjs/toolkit";
const selectItems = (state: RootState) => state.books.items;
export const selectUnread = createSelector([selectItems], (items) => items.filter((b) => !b.read));The input selectors (selectItems) run on every call and must be cheap. The result function only runs when an input changes by reference; otherwise you get the previous array back, same reference. Since Immer preserves the items reference when an unrelated slice changes, the selector stays stable through unrelated actions. The fix exercise below makes you do this.
One detail interviewers like to probe: the cache size. Older Reselect versions remembered only the last call, so one selector shared by several components with different arguments (say, selectBooksByTag(state, tag)) kept evicting itself and recomputing. Reselect 5, the version RTK 2 ships, defaults to weakMapMemoize, which keeps a result per distinct set of arguments, so that sharing pattern now works. lruMemoize is still there if you want the old bounded behavior.
DevTools and time travel#
With the Redux DevTools browser extension installed, configureStore connects automatically. You get a list of every action, the state after each one, a diff of what changed, and a slider to move through history. Jumping back doesn't undo anything in the store's history: DevTools recomputes the state at that point (from its recorded states, or by replaying actions through the reducer) and shows your UI that state. You can skip an action and see what the app would look like without it, export the log, and import someone else's.
All of this depends on the principles holding. A reducer that reads Date.now() or mutates its input makes replay lie. Non-serializable values in state or actions (a Promise, a class instance, a Map) can't be recorded or exported, which is why the serializability check exists.
The sandbox doesn't have the extension, but the idea fits in a few lines: record every state, then render any one of them.
import { useState, useSyncExternalStore } from "react";
import { configureStore, createSlice, type Middleware } from "@reduxjs/toolkit";
const todos = createSlice({
name: "todos",
initialState: [] as string[],
reducers: {
added: (state, action: { payload: string }) => {
state.push(action.payload);
},
removedFirst: (state) => {
state.shift();
},
},
});
// Record [action, state] after every dispatch, like DevTools does.
const history: { type: string; state: string[] }[] = [{ type: "@@init", state: [] }];
const listeners = new Set<() => void>();
const recorder: Middleware = (api) => (next) => (action) => {
const result = next(action);
history.push({ type: (action as { type: string }).type, state: (api.getState() as { todos: string[] }).todos });
listeners.forEach((l) => l());
return result;
};
const store = configureStore({
reducer: { todos: todos.reducer },
middleware: (gdm) => gdm().concat(recorder),
});
const subscribe = (l: () => void) => {
listeners.add(l);
return () => {
listeners.delete(l);
};
};
export default function App() {
const length = useSyncExternalStore(subscribe, () => history.length);
const [at, setAt] = useState<number | null>(null);
const index = at ?? length - 1;
const shown = history[index];
return (
<div>
<button onClick={() => store.dispatch(todos.actions.added("Task " + length))}>Add a task</button>
<button onClick={() => store.dispatch(todos.actions.removedFirst())}>Remove first</button>
<p>
<input type="range" min={0} max={length - 1} value={index} onChange={(e) => setAt(Number(e.target.value))} /> step {index} of{" "}
{length - 1}: <code>{shown.type}</code>{" "}
{at !== null && <button onClick={() => setAt(null)}>Back to live</button>}
</p>
<ul>
{shown.state.map((t, i) => (
<li key={i}>{t}</li>
))}
</ul>
</div>
);
}Add a few tasks, remove one, then drag the slider back. Every past state is still intact, because Immer never mutated any of them: each history entry holds a reference to an immutable snapshot. That's the real enabler of time travel. Immutability makes old states cheap to keep, and pure reducers make them reproducible.
RTK Query, briefly#
RTK Query is Redux Toolkit's answer to the server-state problem. You describe endpoints once; it generates hooks, caches results by endpoint and arguments, deduplicates requests, tracks loading and error per query, and invalidates with tags after mutations. It lives inside your Redux store as a slice plus a middleware, so it shows up in DevTools like everything else.
import { createApi, fakeBaseQuery } from "@reduxjs/toolkit/query/react";
import { fakeFetch } from "guide-tools";
export const booksApi = createApi({
reducerPath: "booksApi",
baseQuery: fakeBaseQuery(), // a real app would use fetchBaseQuery({ baseUrl: "/api" })
tagTypes: ["Book"],
endpoints: (build) => ({
getBooks: build.query<{ id: number; title: string }[], void>({
queryFn: async () => ({ data: await fakeFetch("/books") }),
providesTags: ["Book"],
}),
addBook: build.mutation<{ id: number }, { title: string }>({
queryFn: async (body) => ({ data: await fakeFetch("/books", { method: "POST", body }) }),
invalidatesTags: ["Book"], // every getBooks query refetches
}),
}),
});
export const { useGetBooksQuery, useAddBookMutation } = booksApi;
// configureStore({ reducer: { [booksApi.reducerPath]: booksApi.reducer },
// middleware: (gdm) => gdm().concat(booksApi.middleware) })If your app already uses Redux, RTK Query is usually the right server-cache tool, because it shares the store and the DevTools. If it doesn't, TanStack Query is the common choice. Server state compares them properly.
When Redux is the right call in 2026#
Redux is no longer the default answer to "how do I share state in React", and the Redux maintainers say so themselves. With server data moved to a server-cache library and the rest sorted by kind, many apps have little shared client state left, and Zustand or Jotai handle that with a fraction of the ceremony.
Redux earns its keep when:
- The client state is large, interconnected and long-lived: editors, design tools, trading or ops dashboards, offline-first apps, complex multi-step workflows.
- You need the traceability: an audit trail of every change, reproducible bug reports from an action log, time-travel debugging, undo and redo built on the action history.
- Many teams share one codebase and benefit from enforced conventions: every change is an action, every slice has the same shape, DevTools work everywhere.
- You want one tool for client and server state: RTK plus RTK Query in one store.
- You already have Redux: rewriting a working Redux app to Zustand rarely pays. Migrating old hand-written Redux to RTK does.
It's overkill when your shared client state is a theme, a user and a couple of UI flags, when most of your "state" is server data, or when a small team values minimal code over conventions.
Pitfalls#
Check your understanding#
Fill in the three case reducers and the selector in store.ts. Reducers can "mutate" the draft (Immer is on). The checks call the reducer directly, the way you'd unit test a slice, and also click through the UI.
import { configureStore, createSlice, type PayloadAction } from "@reduxjs/toolkit";
export type Book = { id: number; title: string; read: boolean };
export const initialState = {
items: [
{ id: 1, title: "Refactoring", read: true },
{ id: 2, title: "SICP", read: false },
{ id: 3, title: "Crafting Interpreters", read: false },
] as Book[],
};
const booksSlice = createSlice({
name: "books",
initialState,
reducers: {
bookAdded(state, action: PayloadAction<{ id: number; title: string }>) {
// TODO: append a new unread book
},
readToggled(state, action: PayloadAction<number>) {
// TODO: flip `read` on the book with this id
},
bookRemoved(state, action: PayloadAction<number>) {
// TODO: remove the book with this id
},
},
});
export const { bookAdded, readToggled, bookRemoved } = booksSlice.actions;
export const booksReducer = booksSlice.reducer;
export const store = configureStore({ reducer: { books: booksReducer } });
export type RootState = ReturnType<typeof store.getState>;
export const selectUnreadCount = (state: RootState) => {
// TODO: count unread books
return 0;
};Typing in the note box dispatches to a different slice, yet UnreadList re-renders on every keystroke. Fix the selector so typing doesn't re-render the list, while toggling a book still updates it.
import { configureStore, createSelector, createSlice, type PayloadAction } from "@reduxjs/toolkit";
const books = createSlice({
name: "books",
initialState: {
items: [
{ id: 1, title: "Refactoring", read: false },
{ id: 2, title: "SICP", read: false },
{ id: 3, title: "Crafting Interpreters", read: true },
],
},
reducers: {
readToggled(state, action: PayloadAction<number>) {
const b = state.items.find((x) => x.id === action.payload);
if (b) b.read = !b.read;
},
},
});
const notes = createSlice({
name: "notes",
initialState: { text: "" },
reducers: {
noteChanged(state, action: PayloadAction<string>) {
state.text = action.payload;
},
},
});
export const { readToggled } = books.actions;
export const { noteChanged } = notes.actions;
export const store = configureStore({ reducer: { books: books.reducer, notes: notes.reducer } });
export type RootState = ReturnType<typeof store.getState>;
export const selectUnread = (state: RootState) => state.books.items.filter((b) => !b.read);Given this store, what's logged when store.dispatch({ type: "ping" }) runs?
const a: Middleware = () => (next) => (action) => {
console.log("a before");
const r = next(action);
console.log("a after");
return r;
};
const b: Middleware = () => (next) => (action) => {
console.log("b before");
const r = next(action);
console.log("b after");
return r;
};
const store = configureStore({
reducer: (state = 0, action) => {
console.log("reducer");
return state;
},
middleware: (gdm) => gdm().concat(a, b),
});
store.subscribe(() => console.log("subscriber"));Which app most clearly benefits from Redux Toolkit over a lighter store?
An interviewer asks: "Explain how Redux works and when you'd choose it today."
Interview angle
Redux is a single external store with one rule: state changes only by dispatching actions, which a pure reducer turns into new immutable state. Dispatch flows through middleware, where async work and side effects live, then the reducer, then subscribers, and useSelector re-renders only components whose selection changed. Purity and immutability make the action log replayable, which powers DevTools time travel. Redux Toolkit is how you write it now: createSlice with Immer, configureStore with good defaults, createSelector for derived data, RTK Query for server data. It shines for large, long-lived client state and big teams; for a theme and a few flags it's overkill.
Walk me through what happens when a Redux action is dispatched.
Why must reducers be pure and state immutable? What breaks if they aren't?
How can createSlice reducers mutate state if Redux requires immutability?
When do you need createSelector, and how does it work?
Would you choose Redux for a new React app today? Defend your answer.
What's the difference between createAsyncThunk and RTK Query, and when do you use each?
Recap#
- Flux and Redux make data flow one way: views dispatch actions, pure reducers compute new state, subscribers re-render. Every change goes through one door.
- Redux is the toy store with
dispatch(action)and a reducer in place ofsetState. Purity plus immutability make the action log replayable, which is what DevTools time travel uses. - Redux Toolkit is the modern way:
configureStorewith thunk and dev checks,createSlicewith Immer drafts,createAsyncThunkfor async workflows,createSelectorfor stable derived data. - react-redux 9 provides
<Provider>,useSelector(onuseSyncExternalStoreWithSelector) anduseDispatch; select narrowly and memoize derived arrays. - Use RTK Query rather than thunks for server data. Choose Redux for large, interconnected client state, traceability and team conventions, and skip it when shared client state is small.
Sources#
- Redux: Redux Toolkit overview and Why Redux Toolkit is how to use Redux today
- Redux Toolkit: createSlice, configureStore, createAsyncThunk, Writing reducers with Immer, Migrating to RTK 2.0 and Redux 5.0
- Redux: Deriving data with selectors and Middleware
- React Redux: Hooks
- RTK Query: Overview
- Facts checked November 24, 2026.