-
-
Save peter-horvath-ff/6ed8c2e81e7fb95bfe6529778213c53c to your computer and use it in GitHub Desktop.
Zustand basic example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { create } from 'zustand'; | |
import { shallow } from 'zustand/shallow'; | |
interface BearState { | |
bears: number; | |
increasePopulation: () => void; | |
removeAllBears: () => void; | |
} | |
const useBearStore = create<BearState>((set) => ({ | |
bears: 0, | |
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), | |
removeAllBears: () => set({ bears: 0 }), | |
})); | |
function ZustandExample() { | |
const bears = useBearStore((state) => state.bears); | |
const increasePopulation = useBearStore((state) => state.increasePopulation); | |
const removeAllBears = useBearStore((state) => state.removeAllBears); | |
// alternatively you can achieve the same declarations by destructuring the store with the shallow equality check | |
// const { bears, increasePopulation, removeAllBears} = useBearStore( | |
// (state) => ({ bears: state.bears, increasePopulation: state.increasePopulation, removeAllBears: state.removeAllBears}), | |
// shallow, | |
// ); | |
return ( | |
<> | |
<div>Bears: {bears}</div> | |
<button onClick={increasePopulation}>Add Bear</button> | |
<button onClick={removeAllBears}>Remove All Bears</button> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment