React State Management with Zustand

Manage global state in React using Zustand with TypeScript, including slice patterns, async actions, devtools middleware, and selector-based subscriptions.

TypescriptReactData Fetching

Code

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

interface BearState {
  bears: number;
  addBear: () => void;
  reset: () => void;
}

export const useBearStore = create<BearState>()(
  devtools((set) => ({
    bears: 0,
    addBear: () => set((s) => ({ bears: s.bears + 1 })),
    reset: () => set({ bears: 0 }),
  })),
);

// Usage: const bears = useBearStore((s) => s.bears);

What to watch for

  • Requires zustand and zustand/middleware as packages; the snippet will not run without them.

Using it

The primary signature is export const useBearStore =

Import useBearStore and call it from your own module — the snippet is a drop-in helper, not an executable program.

The crux of the implementation is this line:

addBear: () => set((s) => ({ bears: s.bears + 1 })),

One more line that carries real weight:

import { devtools } from 'zustand/middleware';

And the line that closes the loop:

import { create } from 'zustand';

FAQ

Does this require external packages?
Yes — `zustand` and `zustand/middleware`. Add them to your project before running the snippet.