SmartCodingTips

🐻 Zustand – Lightweight Global State for React

Zustand is a minimal, fast, and scalable state management library for React applications. It doesn’t require Context, reducers, or boilerplate code.


πŸš€ 1. Installation


npm install zustand

πŸ“¦ 2. Create a Store

Define your global state using a simple function:


// store.js
import { create } from 'zustand';

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

export default useCounterStore;

🧠 3. Use the Store in Components

Access the state and actions inside your components:


import useCounterStore from './store';

function Counter() {
  const { count, increment, decrement } = useCounterStore();

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  );
}

βš™οΈ 4. Selectively Read State

To avoid unnecessary re-renders, you can subscribe to just part of the store:


const count = useCounterStore((state) => state.count);

βœ… 5. Why Use Zustand?

  • No Provider needed
  • Simple API & great dev experience
  • Fast and reactive
  • Works well with async logic
  • Perfect for small to medium projects