Zustand, a minimal store for Remix
Zustand, a minimal store for Rreactjs,Remix
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. 😍
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 an 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})