Registry / web-framework / zustand-slices

zustand-slices

JSON →
library0.4.0jsnpmunverified

zustand-slices is a utility library designed to introduce an opinionated, TypeScript-friendly slice pattern for Zustand, a minimalist global state management library. As of version 0.4.0, it provides `createSlice` and `withSlices` helpers to structure Zustand stores into modular, reusable "slices." This addresses the complexities often encountered when attempting to implement such patterns with strong TypeScript typing, particularly when following the official Zustand documentation's manual approach. The library is actively developed, with its primary maintainer frequently tweeting about updates and examples, suggesting a consistent, though not strictly scheduled, release cadence focusing on refinement and new features. Its key differentiator is its explicit support for type inference and clean separation of concerns within a Zustand store, leveraging immutable updates via Immer, which is a peer dependency.

npm install zustand-slices
INSTALL
IMPORT
SIG · ZUSTAND-SLICES
Z
zustand-slices
web-frameworkjavascriptv0.4.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

createSlice
import { createSlice } from 'zustand-slices';
const createSlice = require('zustand-slices').createSlice;
Primarily designed for ESM usage. CommonJS `require` might lead to bundler issues or incorrect type inference.
withSlices
import { withSlices } from 'zustand-slices';
const { withSlices } = require('zustand-slices');
Used to compose multiple slices into a single Zustand store. Follows ESM conventions.
create
import { create } from 'zustand';
import { create } from 'zustand-slices';
The core `create` function comes from `zustand` itself, not `zustand-slices`. This library enhances its usage pattern.

This quickstart demonstrates how to define individual state slices using `createSlice`, combine them into a single Zustand store with `withSlices`, and consume both state and actions within a React component. It also highlights distinct reset actions for each slice to avoid naming conflicts.

import { create } from 'zustand'; import { createSlice, withSlices } from 'zustand-slices'; interface CountState { count: number; inc: () => void; resetCount: () => void; } interface TextState { text: string; updateText: (newText: string) => void; resetText: () => void; } const countSlice = createSlice<CountState>()({ name: 'count', value: 0, actions: { inc: () => (prev) => prev + 1, resetCount: () => () => 0, }, }); const textSlice = createSlice<TextState>()({ name: 'text', value: 'Hello', actions: { updateText: (newText: string) => () => newText, resetText: () => () => 'Hello', }, }); // Combine slices and create the store const useStore = create(withSlices(countSlice, textSlice)); // Example component usage (requires React environment) function MyComponent() { const count = useStore((state) => state.count); const text = useStore((state) => state.text); // Destructuring actions from getState() to ensure referential stability const { inc, updateText, resetCount, resetText } = useStore.getState(); return ( <> <p> Count: {count} <button type="button" onClick={inc}> +1 </button> </p> <p> <input value={text} onChange={(e) => updateText(e.target.value)} /> </p> <p> <button type="button" onClick={resetCount}> Reset Count </button> <button type="button" onClick={resetText}> Reset Text </button> </p> </> ); } // To use MyComponent, render it within a React application. // For example, in a simple setup: // import React from 'react'; // import ReactDOM from 'react-dom/client'; // const root = ReactDOM.createRoot(document.getElementById('root')); // root.render(<MyComponent />);
Debug
Known issues
gotchaImmer is a required peer dependency for `zustand-slices` to function correctly with immutable updates, but it is not automatically installed. Failing to install Immer will lead to runtime errors or unexpected state mutations if slice actions expect Immer's draft mechanism.
fix
Explicitly install Immer in your project: `npm install immer` or `yarn add immer`.
affects: >=0.1.0
gotchaWhen combining multiple slices with `withSlices`, be cautious of action name collisions (e.g., two slices both defining a `reset` action). The last slice combined will overwrite previous actions with the same name, leading to unexpected behavior.
fix
Prefix action names (e.g., `resetCount`, `resetText`) or implement a single, combined action that dispatches to specific slice actions if a global reset is desired.
affects: >=0.1.0
gotchaDirectly mutating state within slice actions without leveraging Immer's draft mechanism (when Immer is installed) or explicitly returning a new state object can lead to un-tracked changes and inconsistent state, as Zustand expects immutable updates.
fix
Always use Immer's `draft` parameter if available, or return a new state object (e.g., `(prev) => ({ ...prev, value: newValue })`) for updates to ensure immutability.
affects: >=0.1.0
gotchaTypeScript inference can sometimes be tricky with complex slice patterns and middleware in Zustand. While `zustand-slices` aims to improve this, incorrect generic types or middleware application can still lead to type errors.
fix
Consult the official Zustand TypeScript guide and examples for best practices. Ensure middleware is applied at the combined store level, not within individual slices, for predictable typing.
affects: >=0.1.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'produce')
The Immer peer dependency is not installed, but zustand-slices expects it for immutable state updates.
fix
Install Immer: `npm install immer` or `yarn add immer`.
TS2345: Argument of type '...' is not assignable to parameter of type 'StateCreator<...>'
TypeScript type inference failed, often due to incorrect generic parameters for `createSlice` or `create` when combining complex state shapes or applying middleware.
fix
Carefully review your `StateCreator` generics and ensure consistency across slices and the main store. Explicitly typing `createSlice<T>()(...)` can help guide inference.
Property 'someProperty' does not exist on type '...' (when accessing state)
The state property you are trying to access does not exist on the combined store's type, or there's a typo. This can happen if a slice was not correctly combined or if type inference missed a property.
fix
Verify that all slices are correctly passed to `withSlices` and that the property name matches the slice's defined state. Ensure your TypeScript configuration is strict enough to catch such issues.
Upgrade
Version history
0.4.0latest on npm
Audit
Dependencies
immerrequiredRequired for immutable state updates within slices, enabling a more natural mutable-like syntax in actions.
reactrequiredPeer dependency for usage within React components, as Zustand stores are typically consumed via hooks in a React environment.
zustandrequiredThe core state management library that zustand-slices extends and builds upon.
Agent activity
42 hits · last 30 days
node
33
OpenAI (training)
1
Resources
zustand-slices — npm install zustand-slices · libregistry