WTH is ZUSTAND
Table of contents
Introduction
If you’re a developer , or listen to convos. of devs. you will find them crib about the state management. What is state management ?? Well, just say passing down of values from one compenent to another ( child or sibling ), and managing it’s ‘value’ or state.
ContextAPI or useContext , do solve the problem But then why zustand??
truth is , even idk, let’s learn it together and find out.
Use Zustand in your project
Initialize you react project via
npm create vite@latest
import zustand
npm i zustand
make a file
src/store.ts
, thenimport {create} from "zustand";
Now , initialize a hook, that u want to use globaly. we are using
useCounter
which has count to store value & increment,decrement func. associated with it.→
set
keyword is used to merge the state.import {create} from "zustand"; type CounterStore = { count: number; increment: ()=> void decrement: ()=> void } export const useCounter = create<CounterStore>((set)=>({ count :0, increment: ()=> set(state=>({count: state.count+1})), decrement: ()=> set(state=>({count: state.count-1})), }))
Now we can use
useCounter
anyhere in project.For eg- in App.tsx
→ we can also use values by destructuring
import { useCounter } from "./store" const App = () => { const count = useCounter(state=> state.count) // count {count, increment, decrement} = useCounter() return ( <div>Count is : {count}</div> ) } export default App
Congrats!!! we have used Zustand in our project. 👍 ♥
Subscribe to my newsletter
Read articles from Ethan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ethan
Ethan
Just another coder, tryin to center div