DEV Community

Dhiman_aman
Dhiman_aman

Posted on

1

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay