How to use Zustand for lightweight state management

· Category: React

Short answer

Zustand is a small state management library that uses a simple store object and a useStore hook to read and update global state with minimal boilerplate.

Steps

  1. Create a store with create(set => ({ ... })).
  2. Subscribe to slices of state in components using the store hook.
  3. Update state by calling actions defined in the store.

Example

import { create } from 'zustand';

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}));

function Counter() {
  const { count, increment } = useStore();
  return <button onClick={increment}>{count}</button>;
}

Tips

  • Zustand supports middleware for persistence and logging.
  • Selectors prevent unnecessary re-renders when only a slice changes.
  • It works outside React, making it great for module-level state.