React Mastery / Advanced Concepts

Zustand - State Management

❓What is Zustand?

  • Zustand is a small, fast, and scalable state management library for React.

  • It offers a simple, unopinionated API based on React hooks.

  • Zustand serves as a centralized store for managing application state with minimal boilerplate.

  • It emphasizes immutability by default and uses proxies for fine-grained dependency tracking, ensuring efficient re-rendering of components.


👉 Key Features

  • No Provider Needed: Unlike Redux, Zustand does not require wrapping your app component with a provider.

  • Simple API: The entire store is a hook created with create().

  • Modular State Slices: You can define separate slices of state inside your store for better structure.

  • Selective Subscriptions: Components can subscribe to parts of the state and only re-render when those parts change.

  • Middleware Support: Zustand supports middleware for logging, persisting state, or handling async actions.

  • Access state inside and outside React components: State can be accessed and modified both from React hooks and external functions.


✅ Basic Usage

🤝 Installation

npm install zustand
*# or*
yarn add zustand

💡Creating a Store

src/store/useCounterStore.js

import create from 'zustand';

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

export default useStore;
  • create takes a function that returns an object representing your state and actions.

  • set is used to update the state immutably.

🧠 Using the Store in Components

src/Counter.js

import useStore from './store';

function Counter() {
  const count = useStore((state) => state.count);
  const increment = useStore((state) => state.increment);

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
  • Using a selector function inside the hook ensures components only re-render on relevant state changes.



👍 Managing Complex or Nested State

  • Zustand supports nested state objects, and you can create actions to update nested state immutably.

Example:

const useStore = create((set) => ({
  user: {
    name: '',
    address: {
      street: '',
      city: '',
    },
  },
  updateUser: (newUser) => set((state) => ({ user: { ...state.user, ...newUser } })),
  updateAddress: (newAddress) =>
    set((state) => ({ user: { ...state.user, address: { ...state.user.address, ...newAddress } } })),
}));

🤝 Middleware and Extensions

  • Zustand can be enhanced with middleware like devtools for Redux DevTools integration, persistence middleware for storing state in localStorage, and more.

👉Example with devtools middleware:

import create from 'zustand';
import { devtools } from 'zustand/middleware';

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

🚀 Advantages of Zustand

  • Minimal Boilerplate: Straightforward API for defining stores and actions.

  • Performance: Efficient updates with selective subscriptions to state slices.

  • Flexibility: Works great with both small and large React applications.

  • Easy to Learn: Simpler than Redux and less opinionated.

  • Works Outside React Components: State can be read or modified from anywhere, including non-component code.


Summary

  • Zustand is a modern state management solution for React that provides a centralized store without complex setup.

  • It uses React hooks with an intuitive API to define state and update functions.

  • Supports middleware, nested state management, and selective re-rendering.

  • Suitable for those who want a simple yet scalable alternative to more heavyweight tools like Redux.