-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Home
Getzel edited this page Jul 21, 2021
·
4 revisions
Welcome to the zustand wiki!
When your project is big with different kind of datas, for convenient coding you want to keep small files. So, like combineReducers in Redux, you can split your store in various functions that will be able to access each other, keeping track of global state.
import create from 'zustand'
const createBearSlice = (set, get) => ({
eatFish: () => set((prev) => ({ fishes: prev.fishes > 1 ? prev.fishes - 1 : 0}))
})
const createFishSlice = (set, get) => ({
fishes: 10
})
const useStore = create( (set, get) => ({
...createBearSlice(set, get),
...createFishSlice(set, get)
}))
function App() {
const fishes = useStore(state => state.fishes);
const eatFish = useStore(state => state.eatFish);
return (
<div className="App">
<p>Fishes : {fishes}</p>
<p><button onClick={eatFish}>Eat</button></p>
</div>
);
}
export default App;
Obiously you can structure your code in different files :
https://codesandbox.io/s/new-dawn-vl03k?file=/src/App.js