How to use createComputed to add computed state
mainThe createComputed middleware takes a compute function that transforms your base state into a computed state. This computed state is merged into the store, making its properties available via the Zustand get() function and directly in React components.
Note that the compute function does not handle merging; it simply returns the new computed properties. When using TypeScript, you should define types for both your base Store and your ComputedStore to ensure type safety, especially when accessing computed values via get().
import { createComputed } from "zustand-computed"
type Store = {
count: number
inc: () => void
dec: () => void
}
type ComputedStore = {
countSq: number
}
const computed = createComputed(
(state: Store): ComputedStore => ({
countSq: state.count ** 2,
}),
)
const useStore = create<Store>()(
computed((set, get) => ({
count: 1,
inc: () => set((state) => ({ count: state.count + 1 })),
dec: () => set((state) => ({ count: state.count - 1 })),
// get() has access to ComputedStore properties
square: () => set(() => ({ count: get().countSq })),
})),
)