Skip to content

Instantly share code, notes, and snippets.

@peter-horvath-ff
Created February 14, 2023 15:52
Show Gist options
  • Save peter-horvath-ff/6ed8c2e81e7fb95bfe6529778213c53c to your computer and use it in GitHub Desktop.
Save peter-horvath-ff/6ed8c2e81e7fb95bfe6529778213c53c to your computer and use it in GitHub Desktop.
Zustand basic example
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