Skip to content

v2.0.0-beta.25 - track deltas

Pre-release
Pre-release
Compare
Choose a tag to compare
@charkour charkour released this 04 Sep 02:38
· 35 commits to main since this release

Allows for runtime perf which results in a larger bundle size. More space efficient but less time efficient.

819 B --> 848 B (3.54% increase)

Usage

Store state delta rather than full object

diff?: (pastState: Partial<PartialTState>, currentState: Partial<PartialTState>) => Partial<PartialTState> | null

For performance reasons, you may want to store the state delta rather than the complete (potentially partialized) state object. This can be done by passing a diff function. The diff function should return an object that represents the difference between the past and current state. By default, the full state object is stored.

If diff returns null, the state change will not be tracked. This is helpful for a conditionally storing past states or if you have a doNothing action that does not change the state.

You can write your own or use something like microdiff, just-diff, or deep-object-diff.

const useStore = create<StoreState>(
  temporal(
    (set) => ({
      // your store fields
    }),
    {
      diff: (pastState, currentState) => {
        const myDiff = diff(currentState, pastState);
        const newStateFromDiff = myDiff.reduce(
          (acc, difference) => {
            type Key = keyof typeof currentState;
            if (difference.type === 'CHANGE') {
              const pathAsString = difference.path.join('.') as Key;
              acc[pathAsString] = difference.value;
            }
            return acc;
          },
          {} as Partial<typeof currentState>,
        );
        return isEmpty(newStateFromDiff) ? null : newStateFromDiff;
      },
    },
  ),
);

What's Changed

Full Changelog: v2.0.0-beta.24...v2.0.0-beta.25