Zustand

npm install immer
npm install zustand
  • Much less boilerplate than React Redux with same benefits over useContext

    • Selectively updates components, easy slices

Basics

  • like useSelector, updates based on strict equality

import { create } from 'zustand'

const useStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

function BearCounter() {
  const bears = useStore((state) => state.bears)
    const increasePopulation = useStore((state) => state.increasePopulation)
  return <h1>{bears} around here...</h1>
}

Slices Pattern With Immer

  • Immer makes nested updates easier

    • IE, Since set(() => ({bears: {a: 0})) is shallowly merged, it would override other parts of {bears} so you would need set((state) => ({bears: {...state.bears, a: 0}}))

    • Immer makes it `set((state) => state.bears.a = 0)

store/userSlice.ts

store/index.ts

Advanced

Slices

Nonhook update

Persist Middleware

  • Could autogenerate selectors to turn const bears = useBearStore((state) => state.bears) into the much? better const bears = useBearStore.use.bears()

Last updated