Back to articles

React State Management: From Zero to Zustand Hero

AuthorMajd Muhtaseb08/27/20257 minutes
React State Management: From Zero to Zustand Hero

Introduction to Zustand

React state management can be complex. Libraries like Redux can be overkill for smaller projects. Zustand provides a simple, unopinionated solution for managing your application's state. It's small, fast, and easy to learn.

Why Zustand?

  • Simplicity: Minimal boilerplate.
  • Performance: Optimized re-renders.
  • Scalability: Works well for both small and large projects.
  • Ease of Use: A straightforward API.

Getting Started

Install Zustand using npm or yarn:

npm install zustand
# or
yarn add zustand

Creating a Store

A store in Zustand is a function that returns an object containing your state and actions.

import { create } from 'zustand';

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

export default useStore;

Using the Store in a Component

Access the state and actions from your store within your React components using the useStore hook.

import React from 'react';
import useStore from './store';

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

  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;

Selective Updates

Zustand provides a way to selectively update components only when the specific state they rely on changes. This optimizes performance.

import React from 'react';
import useStore from './store';

function CountDisplay() {
  const count = useStore(state => state.count); // Select only the count value

  return (
    <h1>Count: {count}</h1>
  );
}

export default CountDisplay;

Persisting State

Zustand doesn't provide persistence out of the box, but you can easily integrate persistence using middleware. Here's an example using zustand/middleware:

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

const useStore = create(persist(
  (set, get) => ({
    count: 0,
    increment: () => set((state) => ({ count: state.count + 1 })),
  }),
  {
    name: 'my-app-storage', // unique name
    getStorage: () => localStorage, // (optional) by default the 'localStorage' is used
  }
));

export default useStore;

Conclusion

Zustand offers a clean and efficient approach to state management in React. Its simplicity and performance advantages make it an excellent choice for various projects. Consider it as a viable alternative to more complex solutions like Redux, especially when starting a new project or refactoring existing state logic.