Zustand Computed State Middleware

0.1.3 · maintenance · verified Wed Apr 22

Zustand Computed State Middleware is a lightweight utility designed to seamlessly integrate derived or computed state into Zustand stores. It enables developers to define functions that calculate new state values based on the existing store state, automatically merging these computed values back into the primary store. This allows computed properties to be accessed directly alongside regular state, simplifying state management logic. The current stable version of this specific middleware is 0.1.3, representing an initial release focused on core functionality and ease of use. However, a different package with similar functionality, `zustand-computed`, is at version 2.1.1 and has seen more active development and breaking changes. As a middleware, its release cadence will likely follow its parent library, Zustand, or be driven by feature enhancements and bug fixes. A key differentiator is its 'dead simple' approach, providing direct state augmentation without the need for manual selectors in many cases, though it explicitly advises keeping computed functions light due to their re-evaluation on every state change to prevent performance bottlenecks. It ships with full TypeScript support, requiring explicit type definitions for robust usage.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create a Zustand store with computed state using the middleware and use it in a React component, showcasing basic increment and derived values.

import create from 'zustand';
import { computed } from 'zustand-middleware-computed-state';
import React from 'react';
import ReactDOM from 'react-dom/client';

const useStore = create(
  computed(
    (set) => ({
      count: 0,
      inc: () => set((state) => ({ count: state.count + 1 })),
    }),
    (state) => {
      function isEnough() {
        if (state.count > 100) {
          return 'Is enough';
        } else {
          return 'Is not enough';
        }
      }

      return {
        computedCount: state.count + 10,
        isEnough: isEnough(),
      };
    }
  )
);

function Counter() {
  const { count, computedCount, isEnough, inc } = useStore();

  return (
    <div>
      <button onClick={inc}>Increment</button>
      <div>count: {count}</div>
      <div>computedCount: {computedCount}</div>
      <div>isEnough: {isEnough}</div>
    </div>
  );
}

// Render the Counter component to a DOM element
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Counter />);

view raw JSON →