The Simplest Zustand Tutorial

The Simplest Zustand Tutorial

Zustand is a small, fast, and scalable state-management library for React, which serves as an alternative to more complex solutions like Redux. The main reason Zustand gained so much traction is its small size and simple syntax compared to Redux.

Understand Zustand Setup

First, you need to install Zustand and TypeScript if you haven't already.

npm install zustand
'or'
yarn add zustand

Zustand provides a create function to define your store. Let's walk through a basic example where we store and manipulate a count value.

Let’s create a file called store.ts where we have a custom hook useCounterStore():

import { create } from "zustand"

type CounterStore = {
    count: number
    increment: () => void
    resetCount: () => void
}

export const useCounterStore = create<CounterStore>((set) => ({
    count: 0
    increment: () => set((state) => ({ count: state.count + 1 })),
    resetCount: () => set({ count: 0 })
}))

In this example:

  • count is a piece of state.

  • increaseCount and resetCount are actions that modify the state.

  • set is a function provided by Zustand to update the store.

Using the Store in a React Component

import React from 'react'
import { useCounterStore } from './store'

const Counter: React.FC = () => {
  const count = useCounterStore((state) => state.count) // Get count from the store
  const increment = useCounterStore((state) => state.increment) // Get the action

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={increment}>Increase Count</button>
    </div>
  )
}

export default Counter;

Here, Counter is a React Component. As you can see, useCounterState() is used to access count and increment.

You can destructure the state instead of getting them directly like how it is in the following:

const {count, increment} = useCounterStore((state) => state)

But this approach makes it less performant. So, the best practice is to get access to the state directly like how it is shown before.

Asynchronous Actions

Making asynchronous action or calling API request to the server is also pretty simple in Zustand. Here, the following code explains it all:

export const useCounterStore = create<CounterStore>((set) => ({
    count: 0
    increment: () => set((state) => ({ count: state.count + 1 })),
    incrementAsync: async () => {
        await new Promise((resolve) => setTimeout(resolve, 1000))
        set((state) => ({ count: state.count + 1 }))
    },
    resetCount: () => set({ count: 0 })
}))

Doesn’t it seem like a generic async function in JavaScript? First of all it runs the asynchronous code and then it sets the state with the given value.

Now, let’s see how you can use it on a react component:

const OtherComponent = ({ count }: { count: number }) => {
  const incrementAsync = useCounterStore((state) => state.incrementAsync)

  return (
    <div>
      {count}
      <div>
        <button onClick={incrementAsync}>Increment</button>
      </div>
    </div>
  )
}

How to access the state outside React Component

Until now, you've only accessed state inside React components. But what about accessing state from outside of React components? Yes, with Zustand you can access state from outside React Components.

const getCount = () => {
  const count = useCounterStore.getState().count
  console.log("count", count)
}

const OtherComponent = ({ count }: { count: number }) => {
  const incrementAsync = useCounterStore((state) => state.incrementAsync)
  const decrement = useCounterStore((state) => state.decrement)

  useEffect(() => {
    getCount()
  }, [])

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

Here, you can see getCount() is accessing to state by getState()

We can set count as well:

const setCount = () => {
  useCounterStore.setState({ count: 10 })
}

Persist Middleware

The persist middleware in Zustand is used to persist and rehydrate the state across browser sessions, typically using localStorage or sessionStorage. This feature allows you to keep the state even after a page reload or when the user closes and reopens the browser. Here’s a detailed breakdown of how it works and how to use it.

Basic Usage of persist

Here’s how to set up a Zustand store with persist:

import create from 'zustand';
import { persist } from 'zustand/middleware';

// Define the state and actions
interface BearState {
  bears: number;
  increase: () => void;
  reset: () => void;
}

// Create a store with persist middleware
export const useStore = create<BearState>(
  persist(
    (set) => ({
      bears: 0,
      increase: () => set((state) => ({ bears: state.bears + 1 })),
      reset: () => set({ bears: 0 }),
    }),
    {
      name: 'bear-storage', // Name of the key in localStorage
    }
  )
);

The state is saved under the key "bear-storage" in localStorage. Now, even if you refresh the page, the number of bears will persist across reloads.

By default, persist uses localStorage, but you can change it to sessionStorage or any other storage system. There are many things to cover on the topic of persisting state in Zustand. You will get a detailed tutorial/post on this topic, which will follow this post.

Conclusion

We all know how great is Redux as a state management tool. But Redux possess a kinda complex and large boilerplate. That is why more and more developers are choosing Zustand as their state management tool which is simple and scale-able.

But still you will see Redux is more recommended for seriously complex and nested state management.