DEV Community

Odukwe Precious Chiemeka
Odukwe Precious Chiemeka

Posted on

How to Handle State Management in Your React Application Using Zustand

State management is a fundamental aspect of building any React application. It is the storing and manipulating of the data used to render a web application's components. When working on a large project, state management can quickly become cumbersome and time-consuming. For this reason, it is preferable to use libraries designed to simplify state management.

Zustand is a lightweight library that provides a fast and scalable solution to state management. Zustand uses hooks to manage state and doesn’t require much boilerplate code. This article will provide information on handling state management in a React application using zustand.

Setting Up Zustand

To make use of zustand, you first have to install it; you install it by running the following command on your project’s terminal:

npm install zustand
Enter fullscreen mode Exit fullscreen mode

After installing the library, you create a store. A store holds all the states and their functions used in your project. You create a store using the create function from the zustand library.

Like so:

import { create } from 'zustand';

const useStore = create( set => ({
    count: 0,
}))

export default useStore;
Enter fullscreen mode Exit fullscreen mode

The create method takes a callback function as its argument. The callback function is used to define the initial state of the store. In this case, the initial state of the store is an object with a single property called count, which is set to 0. The useStore function is a hook that can be used anywhere in your application to access the store.

Accessing the Store

To get access to the states stored in the store. You first import the useStore hook into the required component and then bind your state values to your variables.

For example:

import React from 'react';
import useStore from './store';

function App() {

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

    return (
        <p>{count}</p>
    )
}
Enter fullscreen mode Exit fullscreen mode

After importing the useStore hook, you bind your state value count to the variable count. Rendering your application will cause the number 0 to display on your screen.

Updating your state using the set function

You can change the value of your state by modifying the store. To do this, you will create two properties, an addCount, and a subtractCount property, and add them to the store. These properties are functions that can be used to update your state values.

Like so:

import { create } from 'zustand';

const useStore = create( set => ({
    count: 0,
    addCount: () => set( state => ({ count: state.count + 1}) ),
    subtractCount: () => set( state => ({ count: state.count - 1 }) )
  }))

export default useStore;
Enter fullscreen mode Exit fullscreen mode

The two properties, addCount, and subtractCount, are used to update the count state using the set function provided by the zustand library. The set function is a hook that updates the store state; it allows you to update the state by calling the set() method with a new state object.

The addCount function uses the set function to update the count property by incrementing it by 1. The subtractCount function uses the set function to update the count property by decrementing it by 1.

After creating the store and adding the functions to update the state. You will make the state and the functions available in your components:

import React from 'react';
import useStore from './store';

function App() {

    const[ count, incrementCount, decrementCount] = useStore( state => {
        return [state.count, state.addCount, state.subtractCount]
    }); 

    return (
        <p>{count}</p>
        <button onClick={incrementCount}>increment</button>
        <button onClick={decrementCount}>decrement</button>
    )
}
Enter fullscreen mode Exit fullscreen mode

The state value count and its functions addCount, and subtractCount are destructured and assigned to the variables: count, incrementCount, and decrementCount, respectively.

Accessing the state using the get function

The get function is used to access a current state in the store. This function allows different states to use the same values. You use the get function to access a current state in an action without using the set function.

For example:

import { create } from 'zustand';

const useStore = create( (set, get) => ({
    count: 0,
    action: () => {
            const users = get().count
        }
  }))

export default useStore;
Enter fullscreen mode Exit fullscreen mode

In the code block above, the action function retrieves the value of the count state and assigns it to the users variable.

Working with asynchronous Operations

When working with asynchronous operations, such as fetching data from an API, zustand makes it easy. To work with asynchronous operations, you must complete the fetch requests and set the data from the API to the state using the set function.

For example:

import create from 'zustand';

const useStore = create( set => ({
    post: {},
    fetchPost: async () => {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts');
        set( {post: response.json()} )
    }
}))

export default useStore;
Enter fullscreen mode Exit fullscreen mode

Persisting a State using the persist method

The persist method is a middleware that allows you to persist the state of your store so that it is not lost when the user refreshes the page or closes the browser. The persist middleware persists a state by storing it in the browser's local storage. When the component that uses the store is next rendered, it will read the persisted state from local storage and re-hydrate the store.

To use the persist method, you must first import it from the zustand/middleware:

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

const store = set => ({
    colors: ["red", "blue", "green"],
    addColor: (color) => {
        set( (state) => ({
            colors: [...state.colors, color]
        }) )
    }
})

export default const useStore = create( persist( store, {name: 'paint'}) );
Enter fullscreen mode Exit fullscreen mode

You persisted the store. The local storage key is assigned the name ‘paint’. The store contains a state with two properties: colors, an array of colors, and addColor, a function that adds a new color to the array. Since you persisted the store, you do not lose data when adding new items to the state and refreshing the page.

Conclusion

Zustand is a simple, lightweight, and efficient state management library that you can easily integrate into your React application. With zustand, it's easy to manage the state of your React application in a centralized and efficient way. With the information provided in this article, you should be able to integrate zustand into your next React project.

Top comments (0)