@onoxm/zustand-tools
v0.6.7
Published
Library by Zustand + Typescript
Readme
@onoxm/zustand-tools
A TypeScript utility library for Zustand that provides a flexible store hook with multiple selection patterns.
Installation
npm install @onoxm/zustand-tools
# or
yarn add @onoxm/zustand-tools
# or
pnpm add @onoxm/zustand-toolsPrerequisite
Requires zustand (version >= 5) to be installed in your project:
npm install zustandAPI
createStoreHook
Wraps a Zustand useStore into a flexible hook that supports multiple selection patterns, with automatic shallow comparison for performance optimization.
Signature
function createStoreHook<T extends Record<string, unknown>>(
useStore: UseBoundStore<StoreApi<T>>
): {
(): T // Get all state
<R>(selector: (state: T) => R): R // Selector function
<K extends keyof T>(key: K): T[K] // Single key
<K extends keyof T>(keys: K[], include?: true): Pick<T, K> // Multiple keys
setState: StoreApi<T>['setState']
}Usage Example
import { create } from 'zustand'
import { createStoreHook } from '@onoxm/zustand-tools'
// 1. Define your store
const useCounterStore = create<{
count: number
name: string
increment: () => void
decrement: () => void
}>((set) => ({
count: 0,
name: 'Counter',
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}))
// 2. Wrap with createStoreHook
const useCounter = createStoreHook(useCounterStore)
// 3. Use it
function Counter() {
// Get all state
const all = useCounter()
// Selector function
const double = useCounter((state) => state.count * 2)
// Single key
const count = useCounter('count')
// Multiple keys
const { count, name } = useCounter(['count', 'name'])
// Use setState
const handleIncrement = () => {
useCounter.setState((state) => ({ count: state.count + 1 }))
}
return (
<div>
<div>Count: {count}</div>
<button onClick={handleIncrement}>+</button>
</div>
)
}Features
- 🔥 Type-safe with full TypeScript support
- 🎯 Multiple selection patterns: all state, selector, single key, multiple keys
- ⚡ Automatic shallow comparison for performance optimization
- 📦 Lightweight with no extra dependencies
Author
ono
License
MIT
