DEV Community

Dhiman_aman
Dhiman_aman

Posted on

How to use the Zustand in ReactJS for State Management?

A small, fast, and scalable bearbones state management solution. Zustand has a comfy API based on hooks. It isn't boilerplatey or opinionated, but has enough convention to be explicit and flux-like.

Installation

Install Zustand Library in your ReactJS Project.
Zustand is available as a package on NPM for use:

npm install zustand
Enter fullscreen mode Exit fullscreen mode
  • 1. Create a File store.js in src and paste below code

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

const useApp = ((set) => ({
    count: 0,
    increment: () => set((state) => ({ count: state.count + 1 })),
    decrement: () => set((state) => ({ count: state.count - 1 })),
}));

const useAppStore = create(
    devtools(
        persist(useApp, {
            name: 'test'
        })
    )
)

export default useAppStore;

Enter fullscreen mode Exit fullscreen mode
  • 2. Import the useAppStore in App.js File
 const { count, increment, decrement } = useAppStore();
Enter fullscreen mode Exit fullscreen mode
  • 3. Create a two button for testing your increment and decrement
<h1>Count: {count}</h1>
                <button onClick={increment}>Increment</button>
                <button onClick={decrement}>Decrement</button>
Enter fullscreen mode Exit fullscreen mode

Done.

Plese Vote and React on our posts.

Top comments (0)