Documentation Index
Fetch the complete documentation index at: https://mintlify.com/LegendApp/legend-state/llms.txt
Use this file to discover all available pages before exploring further.
useObserve is a React hook that runs a callback function whenever tracked observables change. It’s similar to useEffect but automatically tracks observable dependencies.
Usage
Signature
Parameters
Single callback form
A function that runs when any tracked observables change. The function automatically tracks any observables accessed with
.get().The callback receives an ObserveEvent object with:previous: The previous valuevalue: The current value (if tracking a specific observable)num: The number of times this observer has fired
Selector + reaction form
A function or observable to track. Changes to this selector trigger the reaction.
A function that runs when the selector changes. Receives the same
ObserveEvent object.If omitted, the selector function itself is treated as both the tracker and the side effect.Options
Configuration options.
Returns
A cleanup function that stops observing. Called automatically when the component unmounts.
Examples
Basic side effect
With selector and reaction
Multiple observables
With dependencies
Run immediately
Async effects
Manual cleanup
Access event metadata
Behavior
Automatic tracking
useObserve automatically tracks any observables accessed with .get() during execution:
Selector vs single callback
Using a separate selector and reaction can be more efficient:Lifecycle
- Observer is set up on component mount
- Runs when tracked observables change
- Automatically disposed on component unmount
- Recreated if
depschange
Comparison with useEffect
Type Parameters
The type of the tracked value. Inferred from the selector or callback.
Notes
- Does not cause component re-renders (use
useSelectorfor that) - Callbacks are not memoized - they use the latest closure values
- The selector function re-runs on each change to re-track dependencies
- Use
depswhen the observer needs to respond to prop/state changes
Related
- useSelector - Track observables and re-render
- useObservable - Create local observables
- observer - HOC for automatic tracking