A state management utility comparable to Redux, but often preferred to mid-sized projects for its simplicity and ease of use.

Overview

Zustand operates on centralized stores that can be accessed directly via custom hooks generated by Zustand. State is reactive, subscribable, and can be used anywhere, not just React components but in utility functions and whatever else you can imagine.

Creating a store

A store can contain both values and functions that act on the store. Let’s start by scaffolding the contents of the store by defining a type. Notice the type definition for functions.

type BearState = {
  count: number;
  increase: () => void;
  reset: () => void;
};

Then let’s actually create the store which creates a custom hook that comes with optional set and get functions in the store creator callback. Let’s make sure to type it with our state and initialize any values and implement those functions. Notice that the store includes actions as well, meaning you can set new behavior for the actions if desired.

const useBearStore = create<BearState>((set) => ({
  count: 0,
  increase: () => set((state) => ({ count: state.count + 1 })),
  reset: () => set({ count: 0 }),
}));

Using the store

You can access the entire store via the hook we made, e.g. useBearStore(), and any time the store is modified the component using the hook will re-render. Oftentimes, we only want to subscribe to only part of the store called a “slice” to prevent unnecessary re-renders. We can do this by provide a selector to useBearStore(selector) like so:

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

Other features

Reset state

We can write a reset method inside the store to go back to the initial values like so:

useBearStore.getState().reset();

Preventing re-renders