Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/gearonix/zustand-middlewares

Convinient and type-safe solution for configuring Zustand middlewares
https://github.com/gearonix/zustand-middlewares

middleware react ts typescript zustand

Last synced: 30 days ago
JSON representation

Convinient and type-safe solution for configuring Zustand middlewares

Awesome Lists containing this project

README

        

[![npm](https://img.shields.io/npm/v/ts-deepmerge)](https://www.npmjs.com/package/zustand-middlewares)

License


PRs Welcome

Zustand Middlewares
=====================

The library makes it easier to work with [zustand](https://zustand-demo.pmnd.rs/) middlewares.

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

Usage
-----
Install the package
```sh
$ npm install zustand-middlewares
```

Import the `configure` function:
```typescript
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.
```typescript
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](https://github.com/gearonix/zustand-middlewares/tree/main/example) to understand it better.

The idea for creating this library was this [discussion](https://github.com/pmndrs/zustand/discussions/2330).

---

### With vs Without

```typescript
// with helper
const useStore = create({
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()(
persist(
immer(
devtools(
subscribeWithSelector((set) => ({
ids: [],
add: (id: number) => {
set((state) => ({
ids: [...state.ids, id]
}))
}
})),
{ enabled: true }
)
),
{ version: 2, name: 'favorite-repos' }
)
)
```