v2.0.0-beta.25 - track deltas
Pre-releaseAllows 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
- bump deps by @charkour in #122
- feat: add
diff
option to track state deltas by @charkour in #123 - add diffing during undo and redo by @charkour in #125
Full Changelog: v2.0.0-beta.24...v2.0.0-beta.25