Zustand, a minimal store for Rreactjs

In search for a minimal store for React applications.


I have been depending on Context for passing state through components in React and eventually thinks complicated when data is become complex. Move on to beautiful Redux is a bit expensive.

For learning Redux I have spent lots of time and Redux Toolkit, easy to use Redux, saved me a lot.

Even though RTK is ok, it is not a simple library. I am fan of Svelte store and Vuex, Pinia store. Is there any such library for React?

I recently found Zustand a minimal store for React. Love it. 😍

  1. Create a store
  2. Binding
  3. Updating the state

Create a store

Create a store using the create and export the custom hook.

import create from 'zustand'

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

Binding

In your component use the hook. The hook accepts a n arrow functions which will access to the state.

const paw = useBearStore ((state)=>state.bears;

The above statement is Reactive, which means that the changes occurs to the state will reflects. For non reactive purposes us the getState() method.

const paw = useBearStore.getState().bears

Updating the state

For updating the state we can use the setState method.

useBearStore.setState({ bears: 1})

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.