Skip to content

Instantly share code, notes, and snippets.

@zaagan
Created February 16, 2024 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaagan/7f5e5a4aeaa081ee89949b7b781915d8 to your computer and use it in GitHub Desktop.
Save zaagan/7f5e5a4aeaa081ee89949b7b781915d8 to your computer and use it in GitHub Desktop.
Quick example on how to use zustand
// Source: https://github.com/cosdensolutions/code/tree/master/videos/long/zustand-tutorial
// store.ts
import { create } from "zustand";
type CounterStore = {
count: number;
increment: () => void;
incrementAsync: () => Promise<void>;
decrement: () => void;
};
export const useCounterStore = create<CounterStore>((set) => ({
count: 0,
increment: () => {
set((state) => ({ count: state.count + 1 }));
},
incrementAsync: async () => {
await new Promise((resolve) => setTimeout(resolve, 1000));
set((state) => ({ count: state.count + 1 }));
},
decrement: () => {
set((state) => ({ count: state.count - 1 }));
},
}));
// App.tsx
import { useEffect } from "react";
import "./App.css";
import { useCounterStore } from "./store";
const setCount = () => {
useCounterStore.setState({ count: 1 });
};
const App = () => {
const count = useCounterStore((state) => state.count);
return <OtherComponent count={count} />;
};
const OtherComponent = ({ count }: { count: number }) => {
const incrementAsync = useCounterStore((state) => state.incrementAsync);
const decrement = useCounterStore((state) => state.decrement);
useEffect(() => {
setCount();
}, []);
return (
<div>
{count}
<div>
<button onClick={incrementAsync}>IncrementAsync</button>
<button onClick={decrement}>Decrement</button>
</div>
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment