Search code examples
reactjsstate-managementreact-state-managementzustand

Zustand: property derived from other properties in the same state


Consider the following zustand store:

const useStore = ((set) => ({
   property1: 2,
   property2: 3,
   property3: 6,
   //etc.
}))

Where property 3 is a multiple of both property1 and property2. Is it possible to set it up such that property3 automatically updates when either property1 or property2 updates in zustand?


Solution

  • Option 1: You can use the hook inside the React component, which will have it's own state and update when property1 or property2 updates.

    function Component() {
        const property1 = useStore(state => state.property1);
        const property2 = useStore(state => state.property2);
    
        // Just for example, this multiples property 1 by property 2
        const property3 = property1 * property2;
    }
    

    Option 2: You can use zustand-store-addons, which adds computed properties

    import create from 'zustand-store-addons';
    
    const useStore = create(
        (set) => ({
            property1: 2,
            property2: 3
        }),
        // Second object is for the addons
        {
            computed: {
                // Recomputes every time property1 or property2 changes.
                property3() {
                    return this.property1 * property2;
                }
            }
        }
    };
    
    // The useStore state will look like
    {
        property1: 2,
        property2: 3,
        property3: 6
    }
    

    Option 1 will be better if you're using the property only in one component, but if you'd like it to be a global property, option 2 will work better.