Managing State in React with Zustand

ZuZulfikar Achyar
June 18, 2024
Managing State in React with Zustand

Zustand provides a simple, unopinionated way to manage state in React.

Creating a Store

First, install it: npm install zustand

Create a store to hold your state and actions.

import { create } from 'zustand';

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}));

Using the Store in a Component

You can then use the hook in any component to access and update the state.

function BearCounter() {
  const bears = useBearStore((state) => state.bears);
  return <h1>{bears} around here ...</h1>;
}

function Controls() {
  const increasePopulation = useBearStore((state) => state.increasePopulation);
  return <button onClick={increasePopulation}>one up</button>;
}

It's that simple! No providers needed.

Let's build something together.

I'm currently available for freelance work and open to discussing new projects.

Contact Details

zulfikarachyar@gmail.com