Skip to main content

Zustland : a minimal data store to consider for the Next React Project

 I have been depending on Context for passing state through components in React and eventually things complicated when data is become complex. Move on to beautiful Redux but it is much complex to digest.

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. 😍

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}) 

Comments

Popular posts from this blog

Build a Flask-Python web App

Building a dynamic website made so easy with Python -Flask, a Micro FrameWork which helps us to create the websites like Twitter and even more. Forget about the complicated web programming languages, start learning Python. So where you start, Python or Flask ?. I should say, you have to learn basics of how Python first, just have a look at Python.org

Using Image url in Keras image classification

  How to load an image in Keras for machine learning from a url ?