Zustand: A small and fast state management for React and Next.js

28-Feb-2024

Generic badgeGeneric badgeGeneric badge

The concept of state management holds significant importance in the React ecosystem. React components rely on state to effectively handle and represent changes in both data and UI elements during rendering and updates. While Redux has long been the dominant force in state management, there is a growing interest among developers in simpler and more lightweight alternatives like Zustand.

What makes Zustand worth learning? Notably, Zustand stands out for its minimalist API, specifically designed to simplify state management within React components. The process of creating a Zustand store is remarkably straightforward – a single function call suffices, requiring the inclusion of a function that defines the store’s initial state and actions. Leveraging the underlying Immer library, Zustand facilitates direct state modification, eliminating the need for intricate reducer functions.

Let’s delve into how to implement state management using Zustand. The initial step involves installing the library.

npm install zustand

Create a file store.js, and build your store hook.

const useCounterStore = create((set) => ({
  ...
}));

In this function, you should add your initial state and action functions. The set function merges state.

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

After that, you can apply it to any client-side element. The best part is that you are not even need to use a state provider throughout your entire application!

const CounterComponent = () => {
  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>
  );
};

Overall, Creating small to medium-sized applications with Zustand is a breeze and it is definitely worth a try.