Skip to main content

Lesson 9 of 9

Practice & Quiz - State Management

Test your knowledge of Context API, Zustand, TanStack Query, and react-hook-form with Zod via a practical cart store exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - Zustand Cart Store

Practical Exercise - Zustand Cart Store
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

// ─── Types ────────────────────────────────────────────────────
interface CartItem {
  id: number;
  name: string;
  price: number;
  qty: number;
}

interface CartStore {
  items: CartItem[];
  addItem:    (item: Omit<CartItem, 'qty'>) => void;
  removeItem: (id: number) => void;
  updateQty:  (id: number, qty: number) => void;
  clearCart:  () => void;
  totalPrice: () => number;
  totalItems: () => number;
}

// persist middleware - syncs to localStorage automatically
export const useCartStore = create<CartStore>()(
  persist(
    (set, get) => ({
      items: [],

      addItem: (item) =>
        set((state) => {
          const existing = state.items.find((i) => i.id === item.id);
          if (existing) {
            return {
              items: state.items.map((i) =>
                i.id === item.id ? { ...i, qty: i.qty + 1 } : i
              ),
            };
          }
          return { items: [...state.items, { ...item, qty: 1 }] };
        }),

      removeItem: (id) =>
        set((state) => ({ items: state.items.filter((i) => i.id !== id) })),

      updateQty: (id, qty) =>
        set((state) => ({
          items: qty <= 0
            ? state.items.filter((i) => i.id !== id)
            : state.items.map((i) => (i.id === id ? { ...i, qty } : i)),
        })),

      clearCart: () => set({ items: [] }),

      totalPrice: () =>
        get().items.reduce((sum, i) => sum + i.price * i.qty, 0),

      totalItems: () =>
        get().items.reduce((sum, i) => sum + i.qty, 0),
    }),
    { name: 'cart-storage' } // localStorage key
  )
);

// ─── Component - no prop drilling, no Context boilerplate ─────
function CartSummary() {
  const { items, removeItem, totalPrice, totalItems } = useCartStore();
  return (
    <div>
      <h2>Cart ({totalItems()} items)</h2>
      {items.map((item) => (
        <div key={item.id} style={{ display: 'flex', gap: 8 }}>
          <span>{item.name} × {item.qty}</span>
          <span>${(item.price * item.qty).toFixed(2)}</span>
          <button onClick={() => removeItem(item.id)}>✕</button>
        </div>
      ))}
      <strong>Total: ${totalPrice().toFixed(2)}</strong>
    </div>
  );
}

Module Quiz

Module Quiz
Question 1 of 5

Why does React Context cause performance problems when used for high-frequency state?

Tip

Tip

Practice Practice Quiz State Management in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Modern React: Use Hooks instead of class lifecycle methods

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz State Management from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz State Management is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/9 done