Getting Started with Zustand: A Step-by-Step Guide

Rind Devran Tukan
Rind Devran Tukan
< 1 min read
Zustand setup tutorial
Reading Time: < 1 minute

Installation

npm install zustand

Creating a Store

import create from 'zustand';

const useCartStore = create((set) => ({
  items: [],
  addItem: (item) => set((state) => ({ items: [...state.items, item] })),
  clearCart: () => set({ items: [] }),
}));

Using the Store in Components

function Cart() {
  const { items, addItem } = useCartStore();
  return (
    <div>
      {items.map((item) => (
        <p key={item.id}>{item.name}</p>
      ))}
      <button onClick={() => addItem({ id: 1, name: 'Product' })}>
        Add Item
      </button>
    </div>
  );
}

Conclusion

Zustand’s simplicity shines in this basic shopping cart example.

Related Articles

Discover more stories from our blog