Created
February 16, 2024 14:06
-
-
Save zaagan/7f5e5a4aeaa081ee89949b7b781915d8 to your computer and use it in GitHub Desktop.
Quick example on how to use zustand
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
// 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