Log in to GraphQL Editor
Zustand - react state management made easy
Michal

Michał Tyszkiewicz

2/20/2023

Zustand - react state management made easy

While managing state in react isn't exactly a Sisyphean task it can certainly become one if the right tools aren't used. The more complex the application the more complex and time-consuming state management can get, with often-seen issues like passing down data to nested props (or prop-drilling), state inconsistencies and in turn issues with performance and code. That’s why there are a number of handy tools that can help make react state management much easier.

Why stick with Redux?

While many devs are still stuck with Redux various other tools offer numerous advantages over it. It's little wonder why React state managers seem to pop up so often as Redux isn’t held in high regard in the community (to put it very mildly) and most are on the lookout for an alternative. Redux requires a fair amount of boilerplate code, is often unnecessarily verbose even for simple actions and brings a lot of complexity which is usually overkill for smaller applications.

A simple alternative

One such alternative is Zustand a minimalistic state manager from the same developers who made Jotai. the name is simply state in german and just as it implies simplicity is the main approach. It focuses on using hooks to manage state and minimize boilerplate code. The emphasis is on being simpler and quicker to use than Redux or other state managers. It's strong points are pretty appealing:

  • way less boilerplate code (being faster to write should appeal to everyone)
  • no time wasted on writing Context Providers (shorter & simpler code)
  • renders components only when changes happen to the value of the state

What is easily evident from that is that its main aim is simplifying the things that are overly complicated with Redux. That's not all as it also boasts important fixes to:

  • the zombie child problem (a common issue when a component is unmounted, but some of its children are not properly cleaned up - leading to memory leaks and potential errors)
  • react concurrency (Zustand supports React Concurrency and is perfect for use with that feature due to its immutable state updates which ensure that state updates are predictable and consistent)
  • context loss between mixed renderers (a problem that can occur in React when multiple rendering systems or libraries are used and cause errors due to different contexts)

Zustand's docs boast it may be the only state managers to get all of these right and from what I could find that just may be the case.

Installation & usage

Well if you're sold on at least trying out Zustand here the gist of how you get to actually use it. In line with its simplicity-first approach it's really straightforward:

# NPM
npm install zustand

# Yarn
yarn add zustand

after installing this is how we import the createStore function from Zustand:

import { createStore } from 'zustand';

and then use the createStore function to create a new store (in this case a simple function which returns an object representing the initial state of our store):

const store = createStore(() => ({
  count: 0,
}));

Then we define actions that update the state of our store. For this example let's use the standard incremental counter example:

const incrementCount = () => store.set((state) => ({ count: state.count + 1 }));

const decrementCount = () => store.set((state) => ({ count: state.count - 1 }));

From there all we need is Zustand's useStore hook to access the state with our counter:

import { useStore } from 'zustand';

function Counter() {
  const count = useStore((state) => state.count);
  const increment = useStore((state) => state.incrementCount);
  const decrement = useStore((state) => state.decrementCount);

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

Bear necessities

In any case, shorter writing time and simpler state management should be enough of a draw for anyone to want to try it out. You don't have to instantly fall in love with Zustand, but even testing it out should make its simplicity and ease of use shine especially compared to more complex state managers. If anything the main gripe with state managers is not that there are too few of them (quite the opposite in fact). Rather it's the fact that most devs are reluctant to let go of Redux and get on board with anything new due to being afraid it won't get enough steam and will get deprecated in half a year. With Zustand there’s no fear of that happening any time soon as it's being actively developed and maintained with version 4.3.3 coming about barely a couple of weeks ago. So don't be afraid to check it out as well and it just might turn out to be what you were looking for.

Check it out at GithHub: https://github.com/pmndrs/zustand

Check out our other blogposts

The state of GraphQL by Reddit
Robert Matyszewski
Robert Matyszewski
The state of GraphQL by Reddit
10 min read
over 4 years ago
Getting started with GraphQL in Python
Tomek Poniatowicz
Tomek Poniatowicz
Getting started with GraphQL in Python
3 min read
over 4 years ago
What's Design System and why you need one?
Tomek Poniatowicz
Tomek Poniatowicz
What's Design System and why you need one?
2 min read
almost 5 years ago

Ready for take-off?

Elevate your work with our editor that combines world-class visual graph, documentation and API console

Get Started with GraphQL Editor