Zustand: The Simple & Scalable State Management Solution for React

2025-04-13

Zustand: The Minimalist State Management You Didn’t Know You Needed

what is the Zustand ?

Zustand is a state management library. It is compact, fast, and scalable. It is a fairly simple system with little boilerplate code. You can use it with less code than Redux and similar libraries for managing React states.

Why we should use Zustand for our projects ?

1. Simple & Lightweight

  • Minimal API with just a few concepts (createsetget).
  • No boilerplate code compared to Redux.

2. No Need for Providers

  • Unlike Redux or Context API, Zustand doesn’t require wrapping components in a <Provider>.

3. Optimized Re-renders

  • Only re-renders components that use the specific state that changed (no unnecessary updates).

4. Persist State (LocalStorage, etc.)

  • Built-in support for persisting state to localStorage or other storage.

5. TypeScript Support

  • First-class TypeScript support for type-safe state management.

8. Scalable

  • Works well for both small and large applications.

          

Here’s a basic Zustand example :

1. Install Zustand

npm install zustand
# or
yarn add zustand
# or
pnpm add zustand

          

2. Define Types and Create Store (store.ts)

import { create } from "zustand";

// Define the type for the store state
type CounterState = {
  count: number;
  increment: () => void;
  decrement: () => void;
  reset: () => void;
};

// Create the store with TypeScript
const useCounterStore = create<CounterState>((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
  reset: () => set({ count: 0 }),
}));

export default useCounterStore;

          

3. Use the Store in a React Component (Counter.tsx)

import useCounterStore from "./store";

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

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={increment}>Increment (+)</button>
      <button onClick={decrement}>Decrement (-)</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}

export default Counter;

          

Using Zustand Outside React Components

One of Zustand's strengths is that it can be used outside of React components. This is particularly useful for integrating with other parts of your application :

const { getState, setState } = useStore;

// Getting state
console.log(getState().bears);

// Setting state
setState({ bears: 10 });

// Using actions
getState().increasePopulation();

          

Zustand provides a simple, lightweight, and scalable way to manage state in React apps with minimal boilerplate. Its flexibility, performance optimizations, and TypeScript support make it a great alternative to Redux or Context API.

Happy coding! 🚀

sohaibb.dev