EasyEcosystem📖 Theory Question

What is Zustand and how does it compare to Context?

💡

Hint

Store-based state with subscription model — only components subscribing to a specific slice re-render

Full Answer

import { create } from 'zustand';

// Define the store
const useCartStore = create((set, get) => ({
  items: [],
  total: 0,

  addItem: (item) => set(state => ({
    items: [...state.items, item],
    total: state.total + item.price,
  })),

  removeItem: (id) => set(state => {
    const item = state.items.find(i => i.id === id);
    return {
      items: state.items.filter(i => i.id !== id),
      total: state.total - (item?.price ?? 0),
    };
  }),

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

// Consume — component only re-renders when items changes
function CartBadge() {
  const items = useCartStore(state => state.items); // subscribe to slice
  return {items.length};
}

// Another component — only subscribes to total
function CartTotal() {
  const total = useCartStore(state => state.total);
  return ${total};
}

Zustand vs Context:

  • Context — all consumers re-render on any context change. Fine for low-frequency updates (theme, auth).
  • Zustand — subscription-based. Component re-renders only when its specific slice changes. Better for frequent updates and large stores.
  • No Provider needed — Zustand store is a module. Import and use anywhere.
💡 Zustand is intentionally minimal. For derived state, just compute it in the component. Use subscribeWithSelector middleware for more granular subscriptions.

More Ecosystem Questions

EasyWhat is the difference between Next.js Pages Router and App Router?EasyWhat is TanStack Query (React Query) and what does it solve?MediumWhat are the key differences between Vite and Create React App?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint