### Install zustand-computed-state Source: https://github.com/yasintz/zustand-computed-state/blob/master/README.md Provides commands to install the zustand-computed-state package using yarn, npm, or pnpm. ```bash yarn add zustand-computed-state npm install zustand-computed-state pnpm add zustand-computed-state ``` -------------------------------- ### Configure ESLint with Type-Aware Rules in Vite/TypeScript Source: https://github.com/yasintz/zustand-computed-state/blob/master/example/README.md This JavaScript configuration extends the ESLint setup for a Vite and TypeScript project. It replaces the default recommended rules with type-aware configurations such as 'recommendedTypeChecked', 'strictTypeChecked', and 'stylisticTypeChecked'. It requires specifying project configuration files like 'tsconfig.node.json' and 'tsconfig.app.json'. ```javascript export default defineConfig([ globalIgnores(['dist']), { files: ['**/*.{ts,tsx}'] extends: [ // Other configs... // Remove tseslint.configs.recommended and replace with this tseslint.configs.recommendedTypeChecked, // Alternatively, use this for stricter rules tseslint.configs.strictTypeChecked, // Optionally, add this for stylistic rules tseslint.configs.stylisticTypeChecked, // Other configs... ], languageOptions: { parserOptions: { project: ['./tsconfig.node.json', './tsconfig.app.json'], tsconfigRootDir: import.meta.dirname, }, // other options... }, }, ]) ``` -------------------------------- ### Enable React-Specific ESLint Rules in Vite/TypeScript Source: https://github.com/yasintz/zustand-computed-state/blob/master/example/README.md This JavaScript configuration integrates 'eslint-plugin-react-x' and 'eslint-plugin-react-dom' into a Vite and TypeScript project's ESLint setup. It applies recommended linting rules for both general React and React DOM usage, enhancing code quality for React components. Similar to the type-aware configuration, it requires project file definitions. ```javascript // eslint.config.js import reactX from 'eslint-plugin-react-x' import reactDom from 'eslint-plugin-react-dom' export default defineConfig([ globalIgnores(['dist']), { files: ['**/*.{ts,tsx}'] extends: [ // Other configs... // Enable lint rules for React reactX.configs['recommended-typescript'], // Enable lint rules for React DOM reactDom.configs.recommended, ], languageOptions: { parserOptions: { project: ['./tsconfig.node.json', './tsconfig.app.json'], tsconfigRootDir: import.meta.dirname, }, // other options... }, }, ]) ``` -------------------------------- ### Integrating Immer Middleware with zustand-computed-state Source: https://github.com/yasintz/zustand-computed-state/blob/master/README.md Demonstrates how to combine the `immer` middleware with `zustand-computed-state` for more convenient state updates. This example shows how Immer simplifies mutations within the `set` function. ```typescript const useStore = create()( devtools( computed( immer((set, get) => ({ count: 1, inc: () => set(state => { // example with Immer middleware state.count += 1; }), dec: () => set(state => ({ count: state.count - 1 })), ...compute(get, state => ({ countSq: state.count ** 2, })), })) ) ) ); ``` -------------------------------- ### Basic Usage of zustand-computed-state with Zustand Source: https://github.com/yasintz/zustand-computed-state/blob/master/README.md Demonstrates how to use the `computed` and `compute` functions from 'zustand-computed-state' to add computed state properties to a Zustand store. It shows how to define state, actions, and computed states, and how `get()` can access these computed states. ```javascript import { computed, compute } from 'zustand-computed-state'; const useStore = create( computed((set, get) => ({ count: 1, inc: () => set(state => ({ count: state.count + 1 })), dec: () => set(state => ({ count: state.count - 1 })), // get() function has access to computed states square: () => set(() => ({ count: get().countSq })), root: () => set(state => ({ count: Math.floor(Math.sqrt(state.count)) })), ...compute(get, state => ({ countSq: state.count ** 2, })), })) ); ``` -------------------------------- ### TypeScript Usage of zustand-computed-state Source: https://github.com/yasintz/zustand-computed-state/blob/master/README.md Illustrates the usage of zustand-computed-state with TypeScript, defining the store's type and integrating computed properties. This example shows type safety for state and computed values. ```typescript import { computed } from 'zustand-computed-state'; type Store = { count: number; inc: () => void; dec: () => void; countSq: number; }; const useStore = create()( computed((set, get) => ({ count: 1, inc: () => set(state => ({ count: state.count + 1 })), dec: () => set(state => ({ count: state.count - 1 })), square: () => set(() => ({ count: get().countSq })), root: () => set(state => ({ count: Math.floor(Math.sqrt(state.count)) })), ...compute(get, state => ({ countSq: state.count ** 2, })), })) ); ``` -------------------------------- ### Getters Pattern with zustand-computed-state Source: https://github.com/yasintz/zustand-computed-state/blob/master/README.md Shows how to use the getters pattern within a Zustand store when integrating with zustand-computed-state. This allows computed properties to be defined as getter methods. ```typescript const useStore = create()( devtools( computed((set, get) => compute({ count: 1, inc: () => set(prev => ({ count: prev.count + 1 })), dec: () => set(state => ({ count: state.count - 1 })), get countSq() { return this.count ** 2; }, }) ) ) ); ``` -------------------------------- ### Slice Pattern with Separate Computed States Source: https://github.com/yasintz/zustand-computed-state/blob/master/README.md Explains how to use the slice pattern with zustand-computed-state, distinguishing computed states for different slices by providing an ID to the `compute` function. This is useful for managing complex state structures. ```diff - ...compute(get, state=>({xSq: state.x **2 })) + ...compute('x_slice', get, state=>({xSq: state.x **2 })) ``` ```typescript type XSlice = { x: number; xSq: number; incX: () => void; }; type YSlice = { y: number; ySq: number; incY: () => void; }; type Store = YSlice & XSlice; const createCountSlice: StateCreator = (set, get) => ({ y: 1, incY: () => set(state => ({ y: state.y + 1 })), ...compute('y_slice', get, state => ({ ySq: state.y ** 2, })), }); const createXySlice: StateCreator = (set, get) => ({ x: 1, incX: () => set(state => ({ x: state.x + 1 })), ...compute('x_slice', get, state => ({ xSq: state.x ** 2, })), }); const store = create()( computed((...a) => ({ ...createCountSlice(...a), ...createXySlice(...a), })) ); ``` -------------------------------- ### Compose Zustand Middleware: Immer, Devtools, and Computed State Source: https://context7.com/yasintz/zustand-computed-state/llms.txt Demonstrates composing computed state middleware with Zustand's Immer and devtools middleware. This allows for mutable state updates using Immer while maintaining computed properties. It requires Zustand, zustand/middleware, and zustand-computed-state. Inputs are defined by the store's state and actions, and outputs are the state properties and computed values. ```typescript import { create } from 'zustand'; import { immer } from 'zustand/middleware/immer'; import { devtools } from 'zustand/middleware'; import { computed, compute } from 'zustand-computed-state'; type Todo = { id: number; text: string; completed: boolean; }; type Store = { todos: Todo[]; addTodo: (text: string) => void; toggleTodo: (id: number) => void; completedCount: number; activeCount: number; }; const useStore = create()( devtools( computed( immer((set, get) => ({ todos: [], addTodo: (text: string) => set(state => { state.todos.push({ id: Date.now(), text, completed: false, }); }), toggleTodo: (id: number) => set(state => { const todo = state.todos.find(t => t.id === id); if (todo) { todo.completed = !todo.completed; } }), ...compute(get, state => ({ completedCount: state.todos.filter(t => t.completed).length, activeCount: state.todos.filter(t => !t.completed).length, })), })) ) ) ); // Usage const store = useStore.getState(); store.addTodo('Buy milk'); store.addTodo('Write code'); console.log(useStore.getState().activeCount); // 2 console.log(useStore.getState().completedCount); // 0 const firstTodo = useStore.getState().todos[0]; store.toggleTodo(firstTodo.id); console.log(useStore.getState().activeCount); // 1 console.log(useStore.getState().completedCount); // 1 ``` -------------------------------- ### Getters Pattern with 'compute' for Concise Computed State in TypeScript Source: https://context7.com/yasintz/zustand-computed-state/llms.txt Shows how to leverage JavaScript getters within the `compute` function for a more concise and object-oriented definition of computed properties like `area`, `circumference`, and `diameter`. This pattern directly accesses state properties for calculation. ```typescript import { create } from 'zustand'; import { computed, compute } from 'zustand-computed-state'; type Store = { radius: number; setRadius: (r: number) => void; area: number; circumference: number; diameter: number; }; const useStore = create()( computed(set => compute({ radius: 5, setRadius: (r: number) => set({ radius: r }), get area() { return Math.PI * this.radius ** 2; }, get circumference() { return 2 * Math.PI * this.radius; }, get diameter() { return this.radius * 2; }, } as Store) ) ); // Usage const store = useStore.getState(); console.log(store.radius); // 5 console.log(store.area); // 78.53981633974483 console.log(store.circumference); // 31.41592653589793 console.log(store.diameter); // 10 store.setRadius(10); const updated = useStore.getState(); console.log(updated.area); // 314.1592653589793 console.log(updated.circumference); // 62.83185307179586 console.log(updated.diameter); // 20 ``` -------------------------------- ### Compute Function - Getters Pattern Source: https://context7.com/yasintz/zustand-computed-state/llms.txt The `compute` function can also be used with JavaScript getters for a more concise and intuitive way to define computed state. ```APIDOC ## `compute` Function - Getters Pattern ### Description Enables defining computed properties using JavaScript getters syntax for more concise and intuitive computed state definitions. ### Usage ```typescript import { create } from 'zustand'; import { computed, compute } from 'zustand-computed-state'; type Store = { radius: number; setRadius: (r: number) => void; area: number; circumference: number; diameter: number; }; const useStore = create()( computed(set => compute({ radius: 5, setRadius: (r: number) => set({ radius: r }), get area() { return Math.PI * this.radius ** 2; }, get circumference() { return 2 * Math.PI * this.radius; }, get diameter() { return this.radius * 2; }, } as Store) ) ); // Usage const store = useStore.getState(); console.log(store.radius); console.log(store.area); console.log(store.circumference); console.log(store.diameter); store.setRadius(10); const updated = useStore.getState(); console.log(updated.area); console.log(updated.circumference); console.log(updated.diameter); ``` ### Parameters This usage of `compute` takes an object where properties can be defined as standard values or JavaScript getters. ### Return Value An object containing the computed properties defined using getters. ``` -------------------------------- ### Zustand Store with Computed State for Shopping Cart Source: https://context7.com/yasintz/zustand-computed-state/llms.txt Defines a Zustand store with basic cart item management and derived computed state for total price and item count. Uses `zustand-computed-state` middleware for efficient calculation of derived values. ```typescript import { create } from 'zustand'; import { computed, compute } from 'zustand-computed-state'; type CartItem = { id: number; name: string; price: number; quantity: number; }; type Store = { items: CartItem[]; addItem: (item: CartItem) => void; updateQuantity: (id: number, quantity: number) => void; removeItem: (id: number) => void; totalPrice: number; itemCount: number; }; const useCartStore = create()( computed((set, get) => ({ items: [], addItem: (item: CartItem) => set(state => ({ items: [...state.items, item] })), updateQuantity: (id: number, quantity: number) => set(state => ({ items: state.items.map(item => item.id === id ? { ...item, quantity } : item ), })), removeItem: (id: number) => set(state => ({ items: state.items.filter(item => item.id !== id) })), ...compute(get, state => ({ totalPrice: state.items.reduce( (sum, item) => sum + item.price * item.quantity, 0 ), itemCount: state.items.reduce((sum, item) => sum + item.quantity, 0), })), })) ); ``` -------------------------------- ### Computed State Middleware with 'computed' and 'compute' in TypeScript Source: https://context7.com/yasintz/zustand-computed-state/llms.txt Demonstrates how to use the `computed` middleware and `compute` function to define derived state properties like `countSq` that automatically update when the base state (`count`) changes. It shows basic state updates and accessing computed values. ```typescript import { create } from 'zustand'; import { computed, compute } from 'zustand-computed-state'; type Store = { count: number; inc: () => void; dec: () => void; countSq: number; }; const useStore = create()( computed((set, get) => ({ count: 1, inc: () => set(state => ({ count: state.count + 1 })), dec: () => set(state => ({ count: state.count - 1 })), ...compute(get, state => ({ countSq: state.count ** 2, })), })) ); // Usage in component const { count, countSq, inc, dec } = useStore(); console.log(count); // 1 console.log(countSq); // 1 inc(); console.log(count); // 2 console.log(countSq); // 4 ``` -------------------------------- ### Standard 'compute' Function Usage for Derived State in TypeScript Source: https://context7.com/yasintz/zustand-computed-state/llms.txt Illustrates the standard usage of the `compute` function to define computed properties such as `fullName` and `isAdult` based on `firstName`, `lastName`, and `age`. It shows how these derived values are updated automatically after state modifications. ```typescript import { create } from 'zustand'; import { computed, compute } from 'zustand-computed-state'; type Store = { firstName: string; lastName: string; age: number; updateFirstName: (name: string) => void; updateLastName: (name: string) => void; updateAge: (age: number) => void; fullName: string; isAdult: boolean; }; const useStore = create()( computed((set, get) => ({ firstName: 'John', lastName: 'Doe', age: 20, updateFirstName: (name: string) => set({ firstName: name }), updateLastName: (name: string) => set({ lastName: name }), updateAge: (age: number) => set({ age }), ...compute(get, state => ({ fullName: `${state.firstName} ${state.lastName}`, isAdult: state.age >= 18, })), })) ); // Usage const store = useStore.getState(); console.log(store.fullName); // "John Doe" console.log(store.isAdult); // true store.updateFirstName('Jane'); console.log(useStore.getState().fullName); // "Jane Doe" store.updateAge(16); console.log(useStore.getState().isAdult); // false ``` -------------------------------- ### Computed Middleware Source: https://context7.com/yasintz/zustand-computed-state/llms.txt The `computed` middleware wraps a Zustand store creator function to enable computed state functionality by intercepting state updates and automatically recalculating derived values. ```APIDOC ## `computed` Middleware ### Description Wraps a Zustand store creator function to enable computed state functionality by intercepting state updates and automatically recalculating derived values. ### Usage ```typescript import { create } from 'zustand'; import { computed, compute } from 'zustand-computed-state'; type Store = { count: number; inc: () => void; dec: () => void; countSq: number; }; const useStore = create()( computed((set, get) => ({ count: 1, inc: () => set(state => ({ count: state.count + 1 })), dec: () => set(state => ({ count: state.count - 1 })), ...compute(get, state => ({ countSq: state.count ** 2, })), })) ); // Usage in component const { count, countSq, inc, dec } = useStore(); console.log(count); console.log(countSq); inc(); console.log(count); console.log(countSq); ``` ### Parameters This middleware takes a store creator function as an argument. The store creator function receives `set` and `get` functions, similar to a standard Zustand store creator. ### Return Value Returns a wrapped store creator function that applies the computed state logic. ``` -------------------------------- ### Compute Function - Standard Usage Source: https://context7.com/yasintz/zustand-computed-state/llms.txt The `compute` function defines computed properties that are automatically recalculated when the state changes. It takes a getter function and a compute function that transforms state into derived values. ```APIDOC ## `compute` Function - Standard Usage ### Description Defines computed properties that are automatically recalculated when the state changes, taking a getter function and a compute function that transforms state into derived values. ### Usage ```typescript import { create } from 'zustand'; import { computed, compute } from 'zustand-computed-state'; type Store = { firstName: string; lastName: string; age: number; updateFirstName: (name: string) => void; updateLastName: (name: string) => void; updateAge: (age: number) => void; fullName: string; isAdult: boolean; }; const useStore = create()( computed((set, get) => ({ firstName: 'John', lastName: 'Doe', age: 20, updateFirstName: (name: string) => set({ firstName: name }), updateLastName: (name: string) => set({ lastName: name }), updateAge: (age: number) => set({ age }), ...compute(get, state => ({ fullName: `${state.firstName} ${state.lastName}`, isAdult: state.age >= 18, })), })) ); // Usage const store = useStore.getState(); console.log(store.fullName); console.log(store.isAdult); store.updateFirstName('Jane'); console.log(useStore.getState().fullName); store.updateAge(16); console.log(useStore.getState().isAdult); ``` ### Parameters - `get`: A function that returns the current state of the store. - `state`: The current state object. ### Return Value An object containing the computed properties. ``` -------------------------------- ### Zustand Slice Pattern with Computed State Source: https://context7.com/yasintz/zustand-computed-state/llms.txt Implements the Zustand slice pattern using computed state for modularity. Each slice manages its own state and computed properties. This pattern requires unique identifiers for each slice's computed properties when using the `compute` function. Dependencies include Zustand and zustand-computed-state. ```typescript import { create, StateCreator } from 'zustand'; import { computed, compute } from 'zustand-computed-state'; type XSlice = { x: number; xSq: number; xCubed: number; incX: () => void; }; type YSlice = { y: number; ySq: number; yCubed: number; incY: () => void; }; type Store = XSlice & YSlice; const createXSlice: StateCreator = (set, get) => ({ x: 1, incX: () => set(state => ({ x: state.x + 1 })), ...compute('x_slice', get, state => ({ xSq: state.x ** 2, xCubed: state.x ** 3, })), }); const createYSlice: StateCreator = (set, get) => ({ y: 1, incY: () => set(state => ({ y: state.y + 1 })), ...compute('y_slice', get, state => ({ ySq: state.y ** 2, yCubed: state.y ** 3, })), }); const useStore = create()( computed((...a) => ({ ...createXSlice(...a), ...createYSlice(...a), })) ); // Usage const store = useStore.getState(); console.log(store.x, store.xSq, store.xCubed); // 1, 1, 1 console.log(store.y, store.ySq, store.yCubed); // 1, 1, 1 store.incX(); console.log(useStore.getState().x); // 2 console.log(useStore.getState().xSq); // 4 console.log(useStore.getState().xCubed); // 8 console.log(useStore.getState().y); // 1 (unchanged) console.log(useStore.getState().ySq); // 1 (unchanged) store.incY(); console.log(useStore.getState().y); // 2 console.log(useStore.getState().ySq); // 4 console.log(useStore.getState().yCubed); // 8 ``` -------------------------------- ### React Shopping Cart Component using Zustand Computed State Source: https://context7.com/yasintz/zustand-computed-state/llms.txt A React component that consumes the `useCartStore` to display shopping cart items, total price, and item count. It includes functionality to add, update quantity, and remove items, with computed state automatically updating the UI. ```typescript // React Component function ShoppingCart() { const { items, totalPrice, itemCount, addItem, updateQuantity, removeItem } = useCartStore(); return (

Shopping Cart ({itemCount} items)

{items.map(item => (
{item.name} ${item.price} updateQuantity(item.id, parseInt(e.target.value))} />
))}
Total: ${totalPrice.toFixed(2)}
); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.