Signal
See source codeTable of contents
A reactive value container that can change over time and track diffs between sequential values.
Signals are the foundation of the @tldraw/state reactive system. They automatically manage dependencies and trigger updates when their values change. Any computed signal or effect that reads from this signal will be automatically recomputed when the signal's value changes.
There are two types of signal:
- Atomic signals - Created using
atom()
. These are mutable containers that can be directly updated usingset()
orupdate()
methods. - Computed signals - Created using
computed()
. These derive their values from other signals and are automatically recomputed when dependencies change.
interface Signal<Value, Diff = unknown> {}
Example
import { atom, computed } from '@tldraw/state'
// Create an atomic signal
const count = atom('count', 0)
// Create a computed signal that derives from the atom
const doubled = computed('doubled', () => count.get() * 2)
console.log(doubled.get()) // 0
count.set(5)
console.log(doubled.get()) // 10
Properties
lastChangedEpoch
The global epoch number when this signal's value last changed.
Note that this represents when the value actually changed, not when it was last computed. A computed signal may recalculate and produce the same value without changing its epoch. This is used internally for dependency tracking and history management.
lastChangedEpoch: number
name
A human-readable identifier for this signal, used primarily for debugging and performance profiling.
The name is displayed in debug output from whyAmIRunning and other diagnostic tools. It does not need to be globally unique within your application.
name: string
Methods
get
Gets the current value of the signal and establishes a dependency relationship.
When called from within a computed signal or effect, this signal will be automatically tracked as a dependency. If this signal's value changes, any dependent computations or effects will be marked for re-execution.
getDiffSince
Gets the sequence of diffs that occurred between a specific epoch and the current state.
This method enables incremental synchronization by providing a list of changes that have occurred since a specific point in time. If the requested epoch is too far in the past or the signal doesn't have enough history, it returns the unique symbol RESET_VALUE to indicate that a full state reset is required.
Parameters
Name | Description |
---|---|
|
The epoch timestamp to get diffs since |
Returns
Diff[] | RESET_VALUE
An array of diff objects representing changes since the epoch, or the unique symbol RESET_VALUE if insufficient history is available