The library makes it easier to work with zustand middlewares.
It's really convenient to use, and also contains amazing typescript support.
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
Checkout the example to understand it better.
The idea for creating this library was this discussion.
// 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' }
)
)