Skip to content

Function: useRx() ​

useRx<Source$, TIn, TOut, ThisArg, Merge>(source$?, options?): readonly [TOut | undefined, UseRx_SetValue<TOut, Merge>, UseRx_Error | undefined, Source$ extends Observable<TIn> ? Source$ : Subject<TIn>]

Defined in: packages/rx-react/src/useRx.ts:45

A React hook that synchronizes component state with an RxJS Observable or Subject.

It manages the subscription lifecycle automatically:

  • Mount/Update: Subscribes to the provided source$ and updates state on every emission.
  • Unmount: Automatically unsubscribes to prevent memory leaks.
  • Initial State: Attempts to extract an initial value from a BehaviorSubject. If not available, it falls back to options.initialValue or the result of the transform function.

Type Parameters ​

Source$ ​

Source$

The type of the source observable/subject.

TIn ​

TIn = UnwrapSourceValue<Source$>

The type of the value received from the source observable.

TOut ​

TOut = TIn

The type of the value emitted by the hook.

ThisArg ​

ThisArg = unknown

The context type for deferred options.

Merge ​

Merge extends boolean = TOut extends object ? boolean : never

Parameters ​

source$? ​

Source$ | (() => void | Source$ | undefined) | null

The RxJS Observable or Subject to monitor. Can also be a factory function. If null/undefined, a new internal Subject is created.

options? ​

UseRx_Options<TIn, TOut, ThisArg, Merge> = {}

Configuration for transformations, merging, and update timing.

Returns ​

readonly [TOut | undefined, UseRx_SetValue<TOut, Merge>, UseRx_Error | undefined, Source$ extends Observable<TIn> ? Source$ : Subject<TIn>]

A tuple containing:

  1. value: The current state value.
  2. setValue: A function to manually update the state (supports functional updates and debouncing).
  3. error: A UseRx_Error object if the stream or transformation fails.
  4. source$: The underlying Observable/Subject.

Example ​

typescript
const [count, setCount, error] = useRx(count$, { initialValue: 0 });