Advanced React 09 · Ecosystem
State management: Zustand and Redux
Kinds of state and how to choose: Context vs. Zustand vs. Redux Toolkit.
Loading lesson…
Advanced React 09 · Ecosystem
Kinds of state and how to choose: Context vs. Zustand vs. Redux Toolkit.
Loading lesson…
So far you can keep state in two places: in a component (useState, useReducer) and in a context that broadcasts it to the whole tree (lesson Hooks 04). That's enough for most things. But try to write an ordinary e-shop with a cart with it: the "Add to cart" button sits by every product deep in the list, and the item count shows up top in the header.
Two distant components need the cart, so we have to put it in their common parent – all the way up in App – and send it down from there through props:
// CartItem = one item in the cart: a product and a quantityinterface Product { id: number; name: string; price: number }interface CartItem { product: Product; qty: number }function App() {// the cart lives up in App, because both the header and the list need itconst [items, setItems] = useState<CartItem[]>([])function add(product: Product) { // add a product to the cartsetItems((items) => [...items, { product, qty: 1 }])}return (<><Header items={items} /> {/* the header doesn't need the cart itself – it just passes it on */}<ProductList onAdd={add} /> {/* the list only passes it on too */}</>)}function Header({ items }: { items: CartItem[] }) {return <header><Logo /><CartBadge items={items} /></header>}function CartBadge({ items }: { items: CartItem[] }) {return <span>🛒 {items.length}</span> // here the cart is finally used}// products = a made-up array of products, say from the serverfunction ProductList({ onAdd }: { onAdd: (p: Product) => void }) {return products.map((p) => <ProductCard key={p.id} product={p} onAdd={onAdd} />)}function ProductCard({ product, onAdd }: { product: Product; onAdd: (p: Product) => void }) {return <div>{product.name} <AddButton product={product} onAdd={onAdd} /></div>}function AddButton({ product, onAdd }: { product: Product; onAdd: (p: Product) => void }) {return <button onClick={() => onAdd(product)}>Add to cart</button> // and here too}
It works, but watch what happens after clicking "Add to cart":
AddButton calls onAdd, which is the add function from App. It calls setItems.App, so React re-renders App – and with it all its children (lesson Advanced React 04): Header, Logo, ProductList, every ProductCard and every button.And there's a second problem: Header, ProductList and ProductCard carry props they don't need themselves. That's prop drilling from lesson Hooks 04 – carrying a message across the whole school.
Context fixes only the second problem. You no longer have to carry props, but a context is a PA system: after every change of the cart, every component that reads the context re-renders – even all the "Add to cart" buttons that only want the add function out of the whole cart. So the cart is missing two things:
That's exactly what state management libraries give you: a store (a place outside components) and a selector (picking a piece). In this lesson you'll meet the two most widespread ones, Zustand and Redux Toolkit.
But careful not to turn the store into a warehouse for everything. When you move house, you don't throw everything into one giant wardrobe in the hall. Milk goes in the fridge, keys in your pocket, documents in a folder, and shared things – spices, say – in the pantry, where the whole family reaches. Each thing has its place according to how it's used.
State is the same. The question "Redux or Zustand?" is like the question "which giant wardrobe should I buy for the hall?". Most state doesn't belong in any global wardrobe. Over the course we've met five places, and each suits a different kind of state. The table is read by rows: on the left the kind of state, then its counterpart at home, an example, and on the right where it goes:
| Kind of state | Like at home | Example | Where it goes |
|---|---|---|---|
| Server | Food in the fridge: bought, with a use-by date | Products, users, orders | TanStack Query (Advanced React 08) |
| In the address | The address on an envelope | Filters, page, selected tab, search | Router – search params (Advanced React 07) |
| Form | Papers on the desk | Field values, errors, submitting | useState / Actions / React Hook Form |
| Local UI | Things in your pocket | An open modal, an expanded section | useState / useReducer in the component |
| Shared client | The shared pantry | The signed-in user, the theme, the cart, an editor in progress | Context, Zustand, Redux… |
"Client" means the state is created right in the app in the browser (the client = the browser), not on the server. A cart is client state: until the customer orders, only their browser knows about it.
useState in it. A few neighbours → state in the common parent (lesson React basics 04). Lots of components in different places in the tree → shared state.Take an e-shop page: a product list with a category filter and a search, an "Add to cart" button, a cart icon in the header, an expandable product detail and a dark mode switch. Let's go through each piece of state and, for each, ask the question that decides where it belongs. The table is read by rows: on the left the piece of state, in the middle the deciding question, on the right the answer:
| State | Question | Where |
|---|---|---|
| The product list | Does it belong to the server, and can it change there? | TanStack Query |
| The selected category, the search text | Should it survive sending the link to a friend? | Search params |
| An expanded product detail | Does anyone besides this card care? | useState in the card |
| The cart contents | Do the header and the page both need it, does it change often? | Zustand / Redux |
| Dark mode | Does everything need it, does it change rarely? | Context (or Zustand too) |
| The number of items in the cart | Can it be calculated from the cart contents? | Nowhere – calculate it |
Why like this:
useState right in it is enough.Out of six things, only one (the cart) really needs a shared store. That's typical.
Remember Hooks 04: Context is a PA system. When the announcement changes, everyone has to listen. If the cart were in Context, every product added would re-render all the components that read the cart – even the "Add to cart" buttons that only want the add function out of the whole cart.
Zustand and Redux handle shared state differently: through a store. A store is a plain object that lives outside the components – in a file of its own, not inside any component function. It holds the shared state (say, the cart items) and the functions that change it (add, empty). It's the shared pantry from the opening table: it isn't in anyone's room, so anyone in the household can reach into it.
But how does a component find out that something changed in the store when no props or Provider connect them? Through a subscription – just like the newspaper subscriber from Hooks 05:
Inside, both Zustand and Redux use useSyncExternalStore from Hooks 05 – but you don't have to write it, the library hides it in its own hook.
A PA system plays everything to everyone. A store works more like a tailored news subscription: each component says exactly what interests it – "only the item count", "only the total price", "only the add function" – and re-renders only when that changes. The small function that picks only what's needed from the whole state is called a selector:
// useCartStore = our cart's hook; section 3 shows how to make it.// For now, all that matters is what we pass to it: a selector.// inside any component, say the cart icon in the headerconst count = useCartStore((state) => state.items.length) // "send me just the count"// └──────── selector ─────────┘// a selector is an ordinary arrow function:// it gets the store's whole state (state) and returns just a piece of it – a number here
After every change the store calls each subscriber's selector and compares the result with the previous one using ===. If it's the same, the component doesn't re-render. An example: there's an apple in the cart and you change its price. The icon's selector returns 1 again, same as last time – 1 === 1, the icon stays as it is.
The table shows what re-renders after a product is added to the cart. The rows are three components of the e-shop, the columns two ways of giving them the cart:
| Component (what it needs from the cart) | Cart in Context | Cart in a store with selectors |
|---|---|---|
| The "Add to cart" button (just the add function) | 🔄 re-renders | ✅ doesn't re-render – add is still the same function |
| The cart icon (item count) | 🔄 re-renders | 🔄 re-renders – the count changed |
| The footer with the price (total price) | 🔄 re-renders | 🔄 re-renders – the price changed |
For one button it doesn't matter. On a page with a hundred products, it's a hundred needless re-renders on every click.
Zustand (German for "state") is a small library for stores. You add it to a project with npm install zustand. Working with it takes three steps: you create the store in a file of its own (step 1), read from it with a selector in components (step 2) and change the state by calling its functions (step 3).
Let's start with what you already know. This is what a cart in one component with useState would look like (lesson React basics 03):
function Cart() {const [items, setItems] = useState([]) // state: an empty cart at the startfunction add(product) { // add a productsetItems((items) => [...items, { product, qty: 1 }])}function clear() { // empty the cartsetItems([])}// …}
It works, but the state and the functions live inside the Cart component. The cart icon in the header can't reach them. A Zustand store is exactly this – the state and the functions that change it – just moved outside components into a file of its own, where anyone can reach for them.
import { create } from 'zustand'export const use___Store = create<___>()((set) => ({___: ___, // state: a name and an initial value___: (___) => set(___), // action: a function that changes the state through set}))
You fill it in with three questions:
items), an empty array [] at the start.add) and emptying the cart (clear). Each change = one function in the store.add it does (new cart = old cart + the product), so set gets a function. For clear it doesn't (an empty cart is always empty), so the new value directly is enough.// file src/stores/cart.tsimport { create } from 'zustand'// Product = one product; in a real app it would come from the serverinterface Product { id: number; name: string; price: number }// the store's shape: the state (items) and the functions that change it (add, clear) – all in one objectinterface CartStore {items: { product: Product; qty: number }[] // the cart items: a product and a quantityadd: (product: Product) => void // add a productclear: () => void // empty the cart}// create makes the store and returns the hook useCartStore; export = components can import itexport const useCartStore = create<CartStore>()((set) => ({items: [], // state: an empty cart at the startadd: (product) => // add a product:set((state) => ({ // state = what's in the store nowitems: [...state.items, { product, qty: 1 }], // a new array: the old items + the new product})),clear: () => set({ items: [] }), // empty: the new value directly}))
Side by side with the useState version, you can see it's the same thing, just written differently:
| What | useState in a component | Zustand store |
|---|---|---|
| The state and its initial value | useState([]) | items: [] |
| What changes the state | setItems | set |
| New value from the old one | setItems((items) => [...items, x]) | set((state) => ({ items: [...state.items, x] })) |
| New value directly | setItems([]) | set({ items: [] }) |
set is the function for changing the state – the counterpart of setItems. The only difference is how you get it. You take the setter from useState out of the array [items, setItems]. Zustand passes you set as a parameter: it calls the function (set) => ({ … }) once, when it creates the store, and gives it set as the argument. It's an ordinary parameter, just like product in add: (product) => ….
The functions add and clear were created inside that function, so they can still see set later, when a component calls them (the closure from lesson JavaScript 02). Don't change the state any other way than through set – only a call to set lets the store know and tell the components.
With useState, the state is one value (the array items). In the store, the state is the whole object – items, add and clear. That's why:
state in set((state) => …) is that whole object; the items are in state.items.{ items: … }). set merges it with the rest of the store, so add and clear stay. (The useState setter would replace the whole value.)What happens when a component calls add(apple) on an empty cart:
// the store now: { items: [], add, clear }add(apple)// 1. add calls set and passes it the arrow (state) => ({ items: [...state.items, { product: apple, qty: 1 }] })// 2. set calls the arrow with what's in the store now: state.items is []// 3. the arrow returns { items: [{ product: apple, qty: 1 }] }// 4. set merges it with the rest of the store:// the store now: { items: [{ product: apple, qty: 1 }], add, clear } ← add and clear stayed// 5. the store tells the components that read the cart (steps 2 and 3)
And the rules from lesson React basics 04 apply: don't change, replace. [...state.items, …] creates a new array. If you wrote state.items.push(…), the array would stay the same (the same reference, lesson JavaScript 09) and nothing would re-render.
set accepts two forms, just like the setter from useState (the updater from React basics 03). Which one you use comes down to one question: do you need the current value to work out the new one?
// clear: the cart will be empty whatever was in it → you don't need the current stateclear: () => set({ items: [] }), // object: "set items to []"// add: new array = old items + the new product → you need the current itemsadd: (product) =>set((state) => ({ items: [...state.items, { product, qty: 1 }] })), // arrow: "take what's there and add"
set merges it into the store straight away. Good when you know the new value in advance (empty the cart, set a theme, switch something to a fixed value).set first calls it with the current state and only then merges what it returns into the store. Good when the new value comes from the old one (add, remove, increase).set({ items: [...items, x] }) work? Inside add there is no variable called items – the items live in the store, not in a component. The arrow is the simple way to get to them: set hands them to you as state.add, clear) are called actions. That's not the same as an action from the reducer in lesson Hooks 03 (an object { type: … } sent through dispatch) – here it's an ordinary function you call.({ … }) – the round brackets around the object are there for the same reason as with useMemo in lesson Advanced React 04: the arrow returns an object, and without the brackets JavaScript would take { as the start of the function body.useCartStore – create returns a hook, so the name starts with use and the rules of hooks apply to it. You don't need a Provider or to wrap the app.create<CartStore>()(…) – <CartStore> tells TypeScript the store's shape (a generic from lesson TypeScript 01). Thanks to it, TypeScript reports an error when you forget clear in the store or write item instead of items. Why there are two sets of brackets is explained in the box below – it's enough to take create<Type>()(…) as a fixed pattern.A component in another file imports the hook (JavaScript 08) and calls it with a selector. The hook returns whatever the selector returns:
// file src/components/CartParts.tsximport { useCartStore } from '../stores/cart' // the hook from step 1 (path: one folder up, then stores/cart)function AddButton({ product }: { product: Product }) {// the selector (s) => s.add: gets the whole store (items, add, clear) and returns just the add functionconst add = useCartStore((s) => s.add)return <button onClick={() => add(product)}>Add to cart</button>}function CartBadge() {// the selector returns the item count: reduce (lesson JavaScript 05) adds up the qty of every item –// it starts at 0 and adds each item i's quantity to the running total nconst count = useCartStore((s) => s.items.reduce((n, i) => n + i.qty, 0))return <span>🛒 {count}</span>}function ClearButton() {const clear = useCartStore((s) => s.clear) // just the clear functionreturn <button onClick={clear}>Empty</button>}
The selector's parameter is usually called just s (as in "store" or "state"). It's the same object as state in set: { items, add, clear } as it is right now. You can choose any name.
No Provider, no props: AddButton can be anywhere in the tree and finds the cart on its own. The prop drilling from the start of the lesson is gone.
Why does AddButton never re-render because of the cart? The add function was created once, when the store was created. set changes only items and leaves add alone, so the selector keeps returning the same function – the === comparison matches. The table shows what happens to the components above after add(apple) on an empty cart:
| Component | The selector returned last time | It returns now | Does it re-render? |
|---|---|---|---|
| AddButton | the add function | the same add function | ✅ no |
| CartBadge | 0 | 1 | 🔄 yes |
| ClearButton | the clear function | the same clear function | ✅ no |
A component doesn't change the state itself – it calls one of the store's actions, like add(product) in AddButton. Let's now put the whole path from the click to the re-render together. What happens after clicking "Add to cart":
onClick calls add(product).add calls set. The store has a new state: a new items array with one item.CartBadge: the selector returned 0 last time, now it returns 1. The result changed → the component re-renders.AddButton and ClearButton: the selectors still return the same functions → they don't re-render.The demo below is the same cart with a few improvements: add on a product that's already in the cart only increases its quantity (map from lesson JavaScript 04), and the selectors are saved in the variables selectCount and selectTotal so they can be used more than once.
What you see: Three components sharing one cart store: buttons for adding, a badge with the item count and the total price. Each card flashes yellow when it re-renders.
Try it:
add function.The takeaway: Each component gets news only about what it picked with its selector. No Provider and no needless re-rendering.
Loading the interactive part…
Middleware is a wrapper around the store's recipe that gives the store an extra ability – like a phone case that adds a wallet while the phone inside stays the same. The two most used:
persist saves the state to localStorage – the browser's memory from lesson JavaScript 08. It saves the state after every change and takes it back out when the page loads, so the cart survives a page reload and even closing the browser.devtools connects the store to Redux DevTools – a browser extension (like React DevTools from the lesson on performance) that shows every change of the store. Despite the name, it works with Zustand too.// file src/stores/settings.tsimport { create } from 'zustand'import { persist, devtools } from 'zustand/middleware'// the store's shape: the theme and the action that changes itinterface Settings {theme: 'light' | 'dark'setTheme: (theme: 'light' | 'dark') => void}export const useSettings = create<Settings>()(devtools( // 3. outer wrapper: a connection to Redux DevToolspersist( // 2. middle wrapper: saving to localStorage(set) => ({ // 1. inside: a plain store recipe as in step 1theme: 'light',setTheme: (theme) => set({ theme }), // { theme } is short for { theme: theme }}),{ name: 'settings' }, // persist's settings: the key it's saved under in localStorage),),)
Read it from the inside out: in the middle is the store recipe you already know, persist wraps it with saving and devtools wraps the result with the DevTools connection. Components use the store exactly as without middleware: useSettings((s) => s.theme).
You may call the useCartStore hook only in a component – the rules of hooks from lesson React basics 03 apply to it. But sometimes you need to reach the store from a plain function that isn't a component. A typical example: placing an order in the file with server calls. The function should take what's in the cart, send it to the server and empty the cart.
With Context that wouldn't work – it lives inside React and you can reach it only from a component. But a store lives outside React, in a plain file, and it has a function for this: getState(). It returns the store's whole contents at this moment – the same object as state in set, that is { items, add, clear }:
// file src/api/orders.ts – a plain file, no componentimport { useCartStore } from '../stores/cart'// sendOrder = a made-up function that sends the items to the server and returns a Promiseexport async function placeOrder() {const items = useCartStore.getState().items // read what's in the cart NOWawait sendOrder(items) // send it to the server and wait for the answer (lesson JavaScript 07)useCartStore.getState().clear() // call the clear action – the cart is emptied}// then in a component, say: <button onClick={placeOrder}>Order</button>
useCartStore.getState – getState is a function "stuck on" the hook. In JavaScript a function can have properties just like an object, and create adds a few of them to the hook it returns. With the dot you take it out of the hook, with the brackets you call it. It isn't a hook call but an ordinary function – that's why it may be anywhere..items – takes the cart items from the returned object..clear() – takes the clear action from the returned object and calls it. It's the same action components get with a selector: it calls set, the store tells its subscribers and the cart icon re-renders to zero.The difference between a selector and getState is the subscription. A selector subscribes and calls the component again after every change. getState looks only once, like peeking into the pantry, and doesn't hear about later changes. The table compares the two – questions in the rows, answers in the columns:
| useCartStore((s) => …) | useCartStore.getState() | |
|---|---|---|
| Where may you use it? | only in a component (it’s a hook) | anywhere – in a component and outside it |
| What does it return? | what the selector picks | the store’s whole contents at this moment |
| When the store changes later… | the component re-renders with the new value | nothing – the old value stays |
| What for? | to show a value on the page | to read or change the state once, outside a component |
In Hooks 03 we explained the reducer with a bank account: nobody overwrites the balance, everyone just reports transactions and one place calculates the new state by the rules. A quick reminder of three terms:
{ type: 'added', text: 'Go shopping' },Redux is exactly that, only not inside one component (like useReducer) but for the whole app: the state lives in a store outside the components, and components take from it with selectors, just like with Zustand. The difference is in how the state changes:
| Zustand | Redux | |
|---|---|---|
| A component wants a change | add(product) | dispatch(added(product)) |
| Who calculates the new state | the action in the store, through set | the reducer, by the action type |
| What stays written down | nothing | every action with its name – a statement of transactions |
The table compares one state change in both libraries: the first row is what the component writes, the second who then calculates the new state, the third what's left after the change. The whole path of one change in Redux looks like this:
component ──dispatch(action)──▶ store ──▶ reducer in the slice ──▶ new state▲ │└───────────── selector: did what I read change? ◀───────────────┘
Translate the Redux terms into bank language. The term is in the left column, its bank counterpart in the middle, and what it is in code on the right:
| Term | At the bank | In Redux |
|---|---|---|
| store | The whole bank with all of a customer's accounts | One object with the whole app's state |
| slice | One account – current, savings… | The part of the state for one area (tasks, the cart) with its own rules |
| action | A transaction: "deposit $500" | { type: 'todos/added', payload: 'Go shopping' } |
| reducer | The rules for calculating the balance | A function (state, action) → new state |
| dispatch | The counter where you hand in a transaction | A function that sends an action to the store |
| selector | Looking at one balance on the statement | A function that picks a piece of the state |
| Redux DevTools | The statement of all transactions | A list of every action that ever came in |
Redux Toolkit (RTK) is the modern, official way to write Redux. Old "plain" Redux needed a lot of repetitive code; the Toolkit writes it for you. You install a pair of packages: npm install @reduxjs/toolkit react-redux (the first is the store and slices, the second connects them to React). We'll build a task list in four steps: a slice (step 1), the store (step 2), connecting it to React (step 3) and using it in a component (step 4).
The template of a slice with blanks:
const ___Slice = createSlice({name: '___', // the slice's nameinitialState: ___, // what the slice starts withreducers: { // the rules: one function = one action___(state, action: PayloadAction<___>) {// change state according to action.payload},},})
You fill it in with three questions, similar to the ones for Zustand:
todos), an empty list at the start.added), a task was ticked (toggled). In Redux, actions are named in the past tense – they describe what happened.// file src/store.tsimport { createSlice, configureStore, type PayloadAction } from '@reduxjs/toolkit'interface Todo { id: number; text: string; done: boolean } // one taskconst todosSlice = createSlice({name: 'todos', // the slice's name – the prefix of action names: 'todos/added'// the starting state; as Todo[] = "an empty array, but it will hold todos"; nextId = the id for the next taskinitialState: { items: [] as Todo[], nextId: 1 },reducers: { // the rules: each function = one actionadded(state, action: PayloadAction<string>) { // an action whose payload is the task's text// take the id from the counter in the state and move the counter up by onestate.items.push({ id: state.nextId, text: action.payload, done: false })state.nextId++},toggled(state, action: PayloadAction<number>) { // an action whose payload is the task's idconst todo = state.items.find((t) => t.id === action.payload) // find the task with that idif (todo) todo.done = !todo.done // and flip done/not done},},})
createSlice gets an object with three things: name (the slice's name), initialState (the slice's starting state) and reducers (the rules). Each function in reducers is one branch of the reducer – instead of a switch with cases fromHooks 03, you write a function named after the action.state (the current state of this slice, not of the whole app) and action (the action that came in).text, id); in Redux it's always called payload. PayloadAction<string> is the type "an action whose payload is a string" – you know the type parameter in angle brackets from generics.[] as Todo[]: from an empty array TypeScript couldn't tell what will be in it. as tells it.nextId is a counter for ids: the first task gets 1, the second 2… Why not use Date.now() for ids as elsewhere? A reducer must be pure – the same state and the same action always give the same result (Hooks 03). Date.now() returns a different number every time it's called, while the counter is part of the state, so the result is always the same.state.items.push(…) and todo.done = !todo.done change the state directly – exactly what we've forbidden all course long. Here, though, it's only seemingly. Redux Toolkit uses the Immer library inside (German for "always"): the state a reducer gets isn't the real state but a draft.
Imagine laying a transparent sheet over the original document and writing your corrections on it. The original stays clean. When you're done, Immer uses the sheet to produce a new copy with all the corrections – a new object, a new array – and that becomes the new state. So the rule "don't change, replace" still applies, Immer just keeps it for you.
| What you want | Without Immer (useState, Zustand) | In createSlice (with Immer) |
|---|---|---|
| Add a task | items: [...items, todo] | state.items.push(todo) |
| Tick a task | items.map((t) => t.id === id ? { ...t, done: !t.done } : t) | todo.done = !todo.done |
The table shows the same change written twice: on the left by hand with copies, on the right the "seemingly changing" way with Immer.
// continuing the file src/store.ts// from the reducer names, createSlice also made functions that make actions – we pull them out by destructuringexport const { added, toggled } = todosSlice.actionsadded('Go shopping') // → { type: 'todos/added', payload: 'Go shopping' } (just makes the object, changes nothing)toggled(3) // → { type: 'todos/toggled', payload: 3 }// a store from the slices: the key todos decides where the slice sits in the stateexport const store = configureStore({reducer: { todos: todosSlice.reducer },})// the whole app's state then looks like this: { todos: { items: [...] } }// another slice would add another key: { todos: …, cart: … }
todosSlice.actions holds a function with the same name for every reducer. It only returns the action object – the change happens when you send it with dispatch. The type is put together from the slice's name and the reducer's name.export const { added, toggled } = … is object destructuring from JavaScript 03: it pulls two properties out into variables of the same name.configureStore puts the slices together into one store and turns on Redux DevTools straight away. The key in the reducer object (todos here) is the name under which you find the slice in the state: state.todos.items.Unlike Zustand, Redux needs a Provider: the store is handed to the app once, in main.tsx, just like a context in Hooks 04. Through it the react-redux hooks find out which store to use:
// file src/main.tsximport { 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}> {/* every component inside App can now reach the store */}<App /></Provider>,)
In components the store is read with the useSelector hook and actions are sent with dispatch, which the useDispatch hook returns. Both come from the react-redux package, but they don't know what your store looks like – s in a selector would have the type unknown, and TypeScript wouldn't let you write s.todos. That's why you make their typed versions once, right below the store. It's a few lines you copy the same way in every project:
// continuing the file src/store.ts (the import goes up top with the others)import { useDispatch, useSelector } from 'react-redux'// the type of the whole state: "exactly what store.getState() returns" → { todos: { items: Todo[] } }export type RootState = ReturnType<typeof store.getState>// the type of this store's dispatch function (it knows about thunks too – functions for loading data, see the box at the end of the section)export type AppDispatch = typeof store.dispatch// the same hooks, only now they know the store's shapeexport const useAppSelector = useSelector.withTypes<RootState>()export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
typeof store.getState is "the type of the getState function" (typeof in a type, from TypeScript 01) and ReturnType<…> takes "the type of what it returns" from it – the same trick as with setInterval in Hooks 02. So you don't write the state type by hand: it's derived from the slices and still fits after you add another one.withTypes returns a copy of the hook that already knows the type. In components you then use only useAppSelector and useAppDispatch.Steps 1–3 together make the whole store file:
// file src/store.ts – the whole thingimport { createSlice, configureStore, type PayloadAction } from '@reduxjs/toolkit'import { useDispatch, useSelector } from 'react-redux'interface Todo { id: number; text: string; done: boolean }// step 1: the sliceconst todosSlice = createSlice({name: 'todos',initialState: { items: [] as Todo[], nextId: 1 },reducers: {added(state, action: PayloadAction<string>) {state.items.push({ id: state.nextId, text: action.payload, done: false })state.nextId++},toggled(state, action: PayloadAction<number>) {const todo = state.items.find((t) => t.id === action.payload)if (todo) todo.done = !todo.done},},})// step 2: the actions and the storeexport const { added, toggled } = todosSlice.actionsexport const store = configureStore({ reducer: { todos: todosSlice.reducer } })// step 3: the types and typed hooksexport type RootState = ReturnType<typeof store.getState>export type AppDispatch = typeof store.dispatchexport const useAppSelector = useSelector.withTypes<RootState>()export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
// file src/TodoApp.tsximport { useAppDispatch, useAppSelector, added, toggled } from './store'function TodoApp() {const todos = useAppSelector((s) => s.todos.items) // subscribing to just this part of the state (a selector)const dispatch = useAppDispatch() // the counter for actionsreturn (<>{/* added('New task') makes the action, dispatch hands it to the store */}<button onClick={() => dispatch(added('New task'))}>Add</button><ul>{todos.map((t) => (<li key={t.id}><label>{/* toggled(t.id) makes an action with this task's id */}<input type="checkbox" checked={t.done} onChange={() => dispatch(toggled(t.id))} />{t.text}</label></li>))}</ul></>)}
What happens after clicking "Add":
added('New task') makes the action { type: 'todos/added', payload: 'New task' }.dispatch hands it to the store.type, the todos slice is found and the added reducer in it.items array.TodoApp gets a new array → it re-renders. A component that subscribes to, say, only the cart doesn't re-render.Derived data (say, only the unfinished tasks) isn't stored anywhere – it's calculated in a selector. But the same trap as with Zustand lurks here: filter returns a new array every time, the === comparison doesn't match and the component re-renders on every change of the store, even when the tasks didn't change at all. createSelector remembers the result and recalculates it only when its inputs change – like useMemo from lesson Advanced React 04, but for the store:
import { createSelector } from '@reduxjs/toolkit'// createSelector([input selectors], (their results) => the derived value)const selectActive = createSelector([(s: RootState) => s.todos.items], // the input: the array of tasks(items) => items.filter((t) => !t.done), // the output: only unfinished ones; recalculated only when items change)// in a component – like any other selectorconst active = useAppSelector(selectActive)
As long as the items array stays the same, selectActive returns the same array as last time and the component doesn't re-render. When items changes (a task is added), filter runs again.
What you see: A task list in a Redux Toolkit store: a slice with the actions added, toggled and filterChanged, typed hooks and a memoised selector for the visible tasks. For the demo the whole example is in one file; in an app the store would be in a file of its own, as in the steps above.
Try it:
selectVisibleTodos selector calculated the visible tasks from items and filter.The takeaway: Redux Toolkit is the reducer from lesson Hooks 03 for the whole app: actions describe what happened, the slice decides how the state changes, and selectors pick what each component needs.
Loading the interactive part…
The difference is easiest to see on the same thing written twice: a cart with one add action and an icon with the item count.
// a simplified cart: items is just an array of products (no quantities)// ───── ZUSTAND ─────────────────────────────────────────────interface CartStore { items: Product[]; add: (product: Product) => void }const useCartStore = create<CartStore>()((set) => ({items: [],add: (product) => set((s) => ({ items: [...s.items, product] })), // an action = a function, immutably}))// a component:const count = useCartStore((s) => s.items.length)const add = useCartStore((s) => s.add)add(product) // you just call the action// ───── REDUX TOOLKIT ───────────────────────────────────────const cartSlice = createSlice({name: 'cart',initialState: { items: [] as Product[] },reducers: {added(state, action: PayloadAction<Product>) {state.items.push(action.payload) // "mutating" the draft – Immer},},})export const { added } = cartSlice.actionsexport const store = configureStore({ reducer: { cart: cartSlice.reducer } })// + typed hooks and <Provider store={store}> in main.tsx (step 3)// a component:const count = useAppSelector((s) => s.cart.items.length)const dispatch = useAppDispatch()dispatch(added(product)) // you make the action and hand it in at the counter
Selectors work the same in both. What differs is how the state changes: in Zustand you call a store function, in Redux you send a named action and a reducer calculates the state. Redux is longer, but every change is written down in the log.
The table compares the three ways of sharing state you now know: Context (possibly with useReducer) from Hooks 04, Zustand and Redux Toolkit. Each row is one question you ask yourself when choosing, and the columns hold the answers for each way.
| Question | Context | Zustand | Redux Toolkit |
|---|---|---|---|
| How to picture it? | A PA system: everyone hears the announcement | A tailored news subscription | A bank account with a statement of transactions |
| Do I have to install anything? | No, it’s part of React | Yes, one small package | Yes, two packages |
| How much code do I write? | Some: a context, a Provider and a custom hook | Little: one call to create | The most: a slice, a store, a Provider and typed hooks |
| After a change, do only the components it concerns re-render? | ❌ No – every component that reads the context re-renders | ✅ Yes, thanks to selectors | ✅ Yes, thanks to selectors (and createSelector for derived data) |
| Will I see every change in Redux DevTools? | ❌ No | ✅ Yes, once you add the devtools middleware | ✅ Yes, straight away with no setup |
| Does it help with server data? | ❌ No – that’s what TanStack Query is for | ❌ No – that’s what TanStack Query is for | ✅ Yes, it has its own RTK Query |
| When to reach for it? | Data that changes rarely: the theme, the signed-in user, the language | Shared state that changes often (a cart, an editor), in a small or medium app | A big app a team works on, where every change has to be traceable |
Two terms from the table deserve an explanation:
This section puts the lesson together into a template to come back to when you write a store of your own. You'll find the same pattern in the Cheat sheets on the React tab.
useState in the common parent.set((state) => ({ … })), no: set({ … }).// file src/stores/cart.tsimport { create } from 'zustand'interface Product { id: number; name: string; price: number } // one product (say from the server)// 1. THE SHAPE: state + actions in one objectinterface CartStore {items: { product: Product; qty: number }[] // state: the items in the cartadd: (product: Product) => void // action: add a productremove: (productId: number) => void // action: remove a product by idclear: () => void // action: empty the cart}// 2. THE STORE: actions change state only through set, immutably (a new array, no push)export const useCartStore = create<CartStore>()((set) => ({items: [], // an empty cart at the startadd: (product) => // the old items + the new oneset((state) => ({ items: [...state.items, { product, qty: 1 }] })),remove: (productId) => // every item except the one with productIdset((state) => ({ items: state.items.filter((i) => i.product.id !== productId) })),clear: () => set({ items: [] }), // the new value directly}))
// 3. USAGE – file src/components/CartParts.tsx// in any component, no Provider; each takes only what it needs with a selectorimport { useCartStore } from '../stores/cart'export function CartBadge() {const count = useCartStore((s) => s.items.length) // a number → re-renders only when the count changesreturn <span>🛒 {count}</span>}export function AddButton({ product }: { product: Product }) {const add = useCartStore((s) => s.add) // the function never changes → the button doesn't re-renderreturn <button onClick={() => add(product)}>Add to cart</button>}
The table is read by rows: on the left what you need, on the right how you write it in the store or a component.
| I want… | I write |
|---|---|
| state with an initial value | items: [] |
| to add an item (new value from the old one) | add: (p) => set((s) => ({ items: [...s.items, p] })) |
| to remove an item | remove: (id) => set((s) => ({ items: s.items.filter((i) => i.id !== id) })) |
| to change one item | rename: (id, name) => set((s) => ({ items: s.items.map((i) => i.id === id ? { ...i, name } : i) })) |
| to set a value directly | clear: () => set({ items: [] }) |
| to read one value in a component | const count = useCartStore((s) => s.items.length) |
| to get an action in a component | const add = useCartStore((s) => s.add) |
| to read two values at once | useCartStore(useShallow((s) => ({ items: s.items, add: s.add }))) |
| to survive a page reload | create<T>()(persist((set) => ({ … }), { name: 'key' })) |
| to read or change it outside a component | useCartStore.getState().clear() |
The "change one item" row uses map (lesson JavaScript 04): it goes through all the items, replaces the one with the right id with a copy that has the change ({ ...i, name }) and returns the others unchanged.
set, and immutably (a new array, a new object).Two components, one shared store. Fill in the action and the reading of the state.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
The first challenge practises section 3: the favourite products are carried through props across several components – move them into Zustand and add saving. The second extends section 4 with asynchronous loading in Redux.
From carrying a message across the whole school to a tailored news subscription – with saving to localStorage. What should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
The complete asynchronous flow in Redux: pending → fulfilled/rejected (the washing machine from the lesson on reducers), typed hooks and a memoised selector. What should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
set, which merges the changes; components read with a selector; no Provider; persist for saving.dispatch, Immer, a Provider and typed hooks, DevTools, RTK Query.useShallow, createSelector).create)create – from the library zustand: a global state library (lesson Advanced React 09).row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).