0.0.1 • Published 1 year ago

zustand-middlewares v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

npm

Zustand Middlewares

The library makes it easier to work with zustand middlewares.

It's really convenient to use, and also contains amazing typescript support.

Usage

Install the package

$ npm install zustand-middlewares

Import the configure function:

import { configure } from 'zustand-middlewares'

const create = configure(
  [persist, { name: 'favorite-repos', version: 2 }],
  immer,
  [devtools, { name: 'repos' }],
  subscribeWithSelector
)

You can also specify default options for each middleware.

Use the create function in each module.

import { create } from './instance'

const useStore = create({ devtools: { enabled: true } })((set) => ({
  ids: [],
  add: (id: number) => {
    set((state) => ({
      ids: [...state.ids, id]
    }))
  }
}))

All middlewares will be picked up and used for every store.

You can override the middleware options for each store. Custom options will be merged with the default ones.

!WARNING Works only with latest versions of zustand, 4.5.0 and higher

Example

Checkout the example to understand it better.

The idea for creating this library was this discussion.


With vs Without

// with helper
const useStore = create<State>({
  impl: (set) => ({
    ids: [],
    add: (id: number) => {
      set((state) => ({
        ids: [...state.ids, id]
      }))
    }
  }),
  devtools: { name: 'my-devtools' }
})

// 💀 without, there may also be some custom middlewares
const useStore = create<State>()(
  persist(
    immer(
      devtools(
        subscribeWithSelector((set) => ({
          ids: [],
          add: (id: number) => {
            set((state) => ({
              ids: [...state.ids, id]
            }))
          }
        })),
        { enabled: true }
      )
    ),
    { version: 2, name: 'favorite-repos' }
  )
)
0.0.1

1 year ago