CodeBlanks Logo Icon CodeBlanks

Zustand cart store

Write a cart store with Zustand.

Moving to Zustand

In this lesson you move the same cart logic to Zustand. Write a store with create, define an addItem action; components access it via the useCart hook.

Zustand does not require a provider like Redux; the store lives at module scope. This makes the code shorter and clearer.

Seeing the same logic solved with different libraries deepens your grasp of state management.

The useCart store

A Zustand store is exported as a hook. In components you read the cart with const items = useCart((s) => s.items) and get the action with const addItem = useCart((s) => s.addItem).

The set function auto-merges the new state; set((s) => ({ items: [...s.items, payload] })) appends a new item to the old list.

Zustand provides immutability automatically, similar to RTK's immer dependency; you do not have to write spread.

Practice Write useCart store

Complete the skeleton. Define useCart store with create. State: { items: [], addItem: (product) => set((s) => ({ items: [...s.items, product] })) }. Export with export const useCart = create(...).

Starter code

App.jsx
import { create } from 'zustand';

// Write useCart store here

Sample solution

App.jsx
import { create } from 'zustand';

export const useCart = create((set) => ({
  items: [],
  addItem: (product) => set((s) => ({ items: [...s.items, product] })),
}));

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is Zustand's advantage over Redux?

App.jsx
No provider = Zustand.
  • It runs faster
  • It writes more code
  • It does not require a provider Correct answer
  • It is only for tests

Explanation: Zustand does not require a provider.

2 addItem action

Question
addItem: (product) => ____((s) => ({ items: [...s.items, product] }));
Answer
addItem: (product) => set((s) => ({ items: [...s.items, product] }));

Explanation: set updates the state.

3 Zustand cart store: match the terms

Term Meaning
create Builds store
useCart Returns hook
set Updates state
selector Relevant piece

All lessons in Advanced