Zustand Computed State Middleware

0.2.0 · active · verified Tue Apr 21

Zustand Computed State is a lightweight, TypeScript-friendly middleware designed for the Zustand state management library. It allows developers to define derived or 'computed' state values that automatically update whenever their base dependencies in the Zustand store change. This eliminates the need for manual re-computation of derived values, simplifying state logic and improving performance by only re-calculating when necessary. The current stable version is 0.2.0, indicating it's in an early but active development phase, with releases likely occurring as features stabilize. Its key differentiator is its straightforward integration into Zustand's middleware chain, providing a clear pattern for computed properties without introducing significant overhead or complex APIs, making it a good choice for applications already leveraging Zustand that require derived state.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates defining a Zustand store with the `zustand-computed-state` middleware to create a `countSq` derived property from `count`, showing both its definition and how it's accessed.

import { create } from 'zustand';
import { computed, compute } from 'zustand-computed-state';

type Store = {
  count: number;
  inc: () => void;
  dec: () => void;
  countSq: number; // Computed state
};

const useStore = create<Store>()(
  computed((set, get) => ({
    count: 1,
    inc: () => set(state => ({ count: state.count + 1 })),
    dec: () => set(state => ({ count: state.count - 1 })),
    // Example: get() can access computed states
    square: () => set(() => ({ count: get().countSq })), 
    root: () => set(state => ({ count: Math.floor(Math.sqrt(state.count)) })),

    // Define computed state 'countSq' based on 'count'
    ...compute(get, state => ({
      countSq: state.count ** 2,
    })),
  }))
);

// Usage in a component (example, not runnable here)
/*
function Counter() {
  const { count, countSq, inc, dec } = useStore();
  return (
    <div>
      <span>Count: {count}</span><br />
      <span>Count Squared: {countSq}</span><br />
      <button onClick={inc}>+1</button>
      <button onClick={dec}>-1</button>
    </div>
  );
}
*/
console.log('Initial state:', useStore.getState());
useStore.getState().inc();
console.log('After increment:', useStore.getState());

view raw JSON →