packages/state/README.md
@tldraw/state is a powerful and lightweight TypeScript library for managing reactive state using signals. It provides fine-grained reactive primitives that automatically track dependencies and efficiently update only what needs to change.
@tldraw/state powers the reactive system at the heart of tldraw, handling everything from canvas updates to collaborative state synchronization. It's designed to work seamlessly with @tldraw/store and has optional React bindings.
Documentation for the most recent release can be found on tldraw.dev/docs, including reference docs. Our release notes can be found here.
For more agent-friendly docs, see our LLMs.txt.
A DOCS.md file is included alongside this README in the published package, with detailed API documentation and usage examples.
Perfect for building reactive UIs, real-time collaborative apps, and complex state machines where performance and predictability matter.
npm install @tldraw/state
import { atom, computed, react } from '@tldraw/state'
// Create reactive state
const name = atom('name', 'World')
const count = atom('count', 0)
// Derive values automatically
const greeting = computed('greeting', () => {
return `Hello, ${name.get()}! Count: ${count.get()}`
})
// React to changes
react('logger', () => {
console.log(greeting.get())
})
// Logs: "Hello, World! Count: 0"
// Update state - reactions run automatically
name.set('tldraw')
// Logs: "Hello, tldraw! Count: 0"
count.set(42)
// Logs: "Hello, tldraw! Count: 42"
Atoms hold raw values and are the foundation of your reactive state:
import { atom } from '@tldraw/state'
// Create atoms with initial values
const user = atom('user', { name: 'Alice', age: 30 })
const theme = atom('theme', 'light')
// Read values
console.log(user.get().name) // 'Alice'
// Update values
user.update((current) => ({ ...current, age: 31 }))
theme.set('dark')
Computed signals derive their values from other signals and update automatically:
import { computed } from '@tldraw/state'
const firstName = atom('firstName', 'John')
const lastName = atom('lastName', 'Doe')
const fullName = computed('fullName', () => {
return `${firstName.get()} ${lastName.get()}`
})
console.log(fullName.get()) // "John Doe"
firstName.set('Jane')
console.log(fullName.get()) // "Jane Doe" - automatically updated!
Reactions run side effects when their dependencies change:
import { react } from '@tldraw/state'
const selectedId = atom('selectedId', null)
// Update UI when selection changes
const stop = react('update-selection-ui', () => {
const id = selectedId.get()
document.getElementById('selected').textContent = id || 'None'
})
selectedId.set('shape-123')
// UI automatically updates
// Clean up when no longer needed
stop()
Batch multiple updates to prevent intermediate reactions:
import { transact } from '@tldraw/state'
const x = atom('x', 0)
const y = atom('y', 0)
const position = computed('position', () => `(${x.get()}, ${y.get()})`)
react('log-position', () => console.log(position.get()))
// Logs: "(0, 0)"
transact(() => {
x.set(10)
y.set(20)
// Reaction runs only once after transaction
})
// Logs: "(10, 20)"
Track changes over time so that dependents can update incrementally instead of recomputing from scratch:
const canvas = atom(
'canvas',
{ shapes: [] },
{
historyLength: 100,
computeDiff: (prev, next) => ({ prev, next }),
}
)
// Remember where you are...
const startEpoch = canvas.lastChangedEpoch
// ... make changes ...
canvas.update((state) => ({ shapes: [...state.shapes, newShape] }))
// ... and get the diffs since then (or RESET_VALUE if the history doesn't reach back that far)
const diffs = canvas.getDiffSince(startEpoch)
Use unsafe__withoutCapture to read values without creating dependencies:
const expensiveComputed = computed('expensive', () => {
const important = importantValue.get()
// Read this without making it a dependency
const metadata = unsafe__withoutCapture(() => metadataAtom.get())
return computeExpensiveValue(important, metadata)
})
Use whyAmIRunning() to understand what triggered an update:
react('debug-reaction', () => {
whyAmIRunning() // Logs dependency tree to console
// Your reaction code...
})
// e.g. in Tldraw's onMount callback, which receives the editor
const selectedShapes = computed('selectedShapes', () => {
return editor.getSelectedShapeIds().map((id) => editor.getShape(id))
})
// React to selection changes; call the returned function to stop
const stop = react('update-property-panel', () => {
const shapes = selectedShapes.get()
updatePropertyPanel(shapes)
})
Install the React bindings:
npm install @tldraw/state-react
import { track, useAtom, useComputed } from '@tldraw/state-react'
// track() re-renders the component when any signal it reads changes
const Counter = track(function Counter() {
const count = useAtom('count', 0)
const doubled = useComputed('doubled', () => count.get() * 2, [count])
return (
<div>
<p>Count: {count.get()}</p>
<p>Doubled: {doubled.get()}</p>
<button onClick={() => count.set(count.get() + 1)}>+</button>
</div>
)
})
For complete API documentation, see DOCS.md.
atom(name, initialValue, options?) - Create a reactive state containercomputed(name, computeFn, options?) - Create a derived valuereact(name, effectFn, options?) - Create a side effecttransact(fn) - Batch state updates@computed - Decorator for computed class propertiesreactor(name, effectFn) - Create a controllable reactionunsafe__withoutCapture(fn) - Read state without creating dependencieswhyAmIRunning() - Debug what triggered an updategetComputedInstance(obj, prop) - Get underlying computed instancesignal.getDiffSince(epoch) - Get the diffs recorded since an epoch (see signal.lastChangedEpoch)Looking for more examples? Check out:
Found a bug? Please submit an issue.
This project is licensed under the MIT License found here. The tldraw SDK is provided under the tldraw license.
Copyright (c) 2024-present tldraw Inc. The tldraw name and logo are trademarks of tldraw. Please see our trademark guidelines for info on acceptable usage.
Find us on Twitter/X at @tldraw. You can contact us by email at [email protected].
Have questions, comments or feedback? Join our discord. For the latest news and release notes, visit tldraw.dev.