Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
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
- Host: GitHub
- URL: https://github.com/gearonix/zustand-middlewares
- Owner: gearonix
- License: mit
- Created: 2024-02-14T08:27:08.000Z (12 months ago)
- Default Branch: main
- Last Pushed: 2024-06-17T02:58:57.000Z (8 months ago)
- Last Synced: 2025-01-09T10:53:18.046Z (30 days ago)
- Topics: middleware, react, ts, typescript, zustand
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/zustand-middlewares
- Size: 542 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 10
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
[![npm](https://img.shields.io/npm/v/ts-deepmerge)](https://www.npmjs.com/package/zustand-middlewares)
![]()
![]()
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 higherExample
-----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' }
)
)
```