ComputeDiff

See source code

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. It's particularly useful for features like undo/redo, synchronization, and change tracking.

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

NameDescription

previousValue

The previous value of the signal

currentValue

The current value of the signal

lastComputedEpoch

The epoch when the previous value was set

currentEpoch

The epoch when the current value was set

Prev
VecLike
Next
ChangeSource