ComputeDiff
A function type that computes the difference between two values of a signal.
This function is used to generate incremental diffs that can be applied to reconstruct state changes over time, so that downstream computeds and effects can update incrementally instead of recomputing from scratch.
The function should analyze the previous and current values and return a diff object that represents the change. If the diff cannot be computed (e.g., the values are too different or incompatible), it should return the unique symbol RESET_VALUE to indicate that a full state reset is required.
type ComputeDiff<Value, Diff> = (
previousValue: Value,
currentValue: Value,
lastComputedEpoch: number,
currentEpoch: number,
) => Diff | RESET_VALUE;Example
import { atom, RESET_VALUE } from "@tldraw/state";
// Simple numeric diff
const numberDiff: ComputeDiff<number, number> = (prev, curr) => curr - prev;
// Array diff with reset fallback
const arrayDiff: ComputeDiff<
string[],
{ added: string[]; removed: string[] }
> = (prev, curr) => {
if (prev.length > 1000 || curr.length > 1000) {
return RESET_VALUE; // Too complex, force reset
}
return {
added: curr.filter((item) => !prev.includes(item)),
removed: prev.filter((item) => !curr.includes(item)),
};
};
const count = atom("count", 0, { computeDiff: numberDiff });Parameters
| Name | Description |
|---|---|
| The previous value of the signal |
| The current value of the signal |
| For an atom, the epoch when the previous value was set. For a computed, the epoch at which it was last checked (the same value its compute function receives), so that |
| The epoch when the current value was set |