React hooks
useObservable()
A React hook that returns the current/latest value from an observable
Signature
function useObservable<T>(observable$: Observable<T>): T | null
function useObservable<T>(
observable$: Observable<T>,
initialValue: T | undefined,
options?: UseObservableOptions,
): T
interface UseObservableOptions {
disabled?: boolean
}disabled pauses the live subscription (later emissions stop updating the component; the last value is kept). It does not skip the render-phase warm-up subscription — see the guide for swapping the observable when you need zero subscriptions.
Example
import {useMemo} from 'react'
import {useObservable} from 'react-rx'
import {interval} from 'rxjs'
function MyComponent() {
const observable = useMemo(() => interval(100), [])
const number = useObservable(observable, 0)
return <>The number is {number}</>
}useObservableEvent()
A React hook that turns an event handler into an observable stream. Pass a function that receives an observable of events and returns an observable of side effects; the hook returns a stable callback you can attach to DOM or component event props.
When the returned callback is invoked, its single argument is emitted into the observable. The pipeline you return is subscribed for the lifetime of the component, and unsubscribed on unmount.
Signature
function useObservableEvent<T, U>(
handleEvent: (arg: Observable<T>) => Observable<U>,
): (arg: T) => voidExample
import {useState} from 'react'
import {useObservableEvent} from 'react-rx'
import {filter, map, tap} from 'rxjs/operators'
const ShowSliderValue = () => {
const [value, setValue] = useState(1)
const handleChange = useObservableEvent((value$) =>
value$.pipe(
// Ignore nullish values
filter(nonNullable),
// Cast to number
map((value) => Number(value)),
// Update local state
tap(setValue),
),
)
return (
<>
<input
type="range"
value={value}
onChange={(event) => handleChange(event.target.value)}
min={1}
max={10}
/>
<div>Value is: {value}</div>
</>
)
}
function nonNullable<T>(v: T): v is NonNullable<T> {
return v != null
}