Skip to content

Splitting the store into separate slices

odedindi edited this page Sep 22, 2021 · 11 revisions

As your project grows with varied forms of data, you might want to keep your files small and manageable. Like combineReducers in Redux, you can split your store into 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;

Look at this code working in a structure with different files:
https://codesandbox.io/s/new-dawn-vl03k?file=/src/App.js


Here is the practice for TypeScript users:

https://github.com/pmndrs/zustand/issues/508#issue-951331506

https://codesandbox.io/s/nostalgic-voice-3knvd?file=/src/App.js