useObservable is a React hook that creates a new observable that persists for the lifetime of the component.
Usage
Signature
Parameters
The initial value of the observable. Can be:
- A plain value
- A function that returns the initial value
- A function that returns a Promise (for async initialization)
- A Promise that resolves to the initial value
undefined.An optional dependency array similar to
useEffect. When provided:- If
valueis a function with one parameter (a lookup table), it will be called with a parameter whenever deps change - Otherwise, the function will be re-evaluated whenever deps change
Returns
An observable object that persists for the lifetime of the component. The observable will be automatically cleaned up when the component unmounts.
Examples
Basic usage
With function initializer
With async initialization
With dependencies
With lookup table
Notes
- The observable is created on the first render and persists for the component’s lifetime
- Tracked observables are automatically deactivated when the component unmounts
- If you need to use the observable across multiple components, create it outside the component with
observable()instead - Also exported as
useLocalObservablefor compatibility
Type Parameters
The type of the observable’s value. When no initial value is provided, the observable will have type
Observable<T | undefined>.Related
- useComputed - Create a computed observable
- useSelector - Subscribe to observable changes
- useObserve - Run side effects when observables change