track
See source codeReturns a tracked version of the given component. Any signals whose values are read while the component renders will be tracked. If any of the tracked signals change later it will cause the component to re-render.
This also wraps the component in a React.memo() call, so it will only re-render when props change OR when any tracked signals change. This provides optimal performance by preventing unnecessary re-renders while maintaining reactivity.
The function handles special React component types like forwardRef and memo components automatically, preserving their behavior while adding reactivity.
function track<T extends FunctionComponent<any>>(
baseComponent: T
): React.NamedExoticComponent<React.ComponentProps<T>>
Example
import { atom } from '@tldraw/state'
import { track, useAtom } from '@tldraw/state-react'
const Counter = track(function Counter(props: CounterProps) {
const count = useAtom('count', 0)
const increment = useCallback(() => count.set(count.get() + 1), [count])
return <button onClick={increment}>{count.get()}</button>
})
// Component automatically re-renders when count signal changes
// Works with forwardRef components
const TrackedInput = track(
React.forwardRef<HTMLInputElement, InputProps>(
function TrackedInput(props, ref) {
const theme = useValue(themeSignal)
return <input ref={ref} style={{ color: theme.textColor }} {...props} />
}
)
)
Parameters
Name | Description |
---|---|
|
The React functional component to make reactive to signal changes |
Returns
React.NamedExoticComponent<React.ComponentProps<T>>
A memoized component that re-renders when props or tracked signals change