Zustand - updating state when another value changes (useEffect equivalent)

288 views Asked by At

I feel like I'm overlooking something really simple here. I'm moving a custom hook over to a store. With my hook I'd use:

useEffect(() => {
    setOriginalRecord({...activeRecord});
}, [activeRecord])

So, any time the activeRecord property is updated, I update the originalRecord. This can happen in several different places. How do I do the equivalent with Zustand? I see Zustand has subscribe methods, but I don't think that's what I'm after. I'm trying to avoid duplicating the setOriginalRecord code in multiple different functions.

Here's an example method in my store:

    setRecords: records => {
        set({
            records: records,
            activeRecord: records[get().recordIndex],
            recordCount: records.length,
            originalRecord: {...records[get().recordIndex]}
        })
    },

I don't like this. I already update activeRecord in that method, so once it's updated I just want originalRecord to be a copy of the activeRecord. Again, this can happen in several methods, so a useEffect equivalent makes sense.

0

There are 0 answers