useReactor
See source codeA React hook that runs a side effect in response to changes in signals (reactive state).
The effect function will automatically track any signals (atoms, computed values) that are accessed during its execution. When any of those signals change, the effect will be scheduled to run again on the next animation frame.
This is useful for performing side effects (like updating the DOM, making API calls, or updating external state) in response to changes in tldraw's reactive state system, while keeping those effects efficiently batched and throttled.
function useReactor(
name: string,
reactFn: () => void,
deps?: any[] | undefined
): void
Example
import { useReactor, useEditor } from 'tldraw'
function MyComponent() {
const editor = useEditor()
// Update document title when shapes change
useReactor(
'update title',
() => {
const shapes = editor.getCurrentPageShapes()
document.title = `Shapes: ${shapes.length}`
},
[editor]
)
return <div>...</div>
}
import { useEditor, useReactor } from 'tldraw'
function SelectionAnnouncer() {
const editor = useEditor()
// Announce selection changes for accessibility
useReactor(
'announce selection',
() => {
const selectedIds = editor.getSelectedShapeIds()
if (selectedIds.length > 0) {
console.log(`Selected ${selectedIds.length} shape(s)`)
}
},
[editor]
)
return null
}
Parameters
Name | Description |
---|---|
|
A debug name for the effect, useful for debugging and performance profiling. |
|
The effect function to run. Any signals accessed in this function will be tracked. |
|
React dependencies array. The effect will be recreated when these change. Defaults to |
Returns
void