Skip to content

RxJS in React: Observables in the UI Data Flow

RxJS does not shine everywhere in React, only where asynchronous events have to be coordinated – debounced input, canceled autocomplete requests, continuous streams. The post shows the few places where observables really pay off, and where useState is perfectly enough.

≈ 10 min readSoftwareFrontendReact

An observable is not a state container. It holds no value that a component could read, and it does not replace useState. It describes an execution that pushes values to its subscribers over time and that can be canceled at any moment. If you take this definition seriously, you have half answered the question of RxJS in React: where it is only about the current value of a field, an observable contributes nothing. It only pays off where the timeline itself becomes the problem.

Editorial note (July 2026): The component-local subscriptions with useEffect and cleanup shown here remain sensible. If, on the other hand, RxJS-based state is read by several components as an external store, React needs a stable snapshot contract, typically via useSyncExternalStore or an adapter library built on it. The post deliberately stays with the coordination of events and does not turn RxJS into a general state solution.

The whole discussion, which usually gets stuck in React teams, hinges on this distinction. If you know RxJS from the Angular world, you often associate it with pipelines that ran across the entire application and that nobody could follow anymore. If you only know streams from the outside, you find them elegant and would pour the entire component state into observables. Both positions miss the narrow area that actually matters: keystrokes that arrive faster than an API responds. Responses that arrive in the wrong order. Connections that just keep sending. I take these three cases apart here – and after that, the places where React’s built-in tools remain the better choice.

A quick framing: what an observable is in this context#

I assume the basics from RxJS: Push and Pull here – that post explains why an observable is a push producer and how it differs from promises and iterators. For the React context, three properties are decisive.

First, an observable is lazy: the code in the subscribe callback only runs when someone actually calls subscribe(). An observable that nobody subscribes to does nothing. Second, a normal observable is cold and unicast by default – every subscription starts its own execution. Third, subscribe() returns a Subscription, and its unsubscribe() ends the execution again.

Taken together, these three points explain why RxJS and the useEffect lifecycle fit together so well: an effect has exactly the structure “set up on mount, clean up on unmount” that an observable needs.

import { Observable } from 'rxjs';

// A cold observable: the callback runs once per subscriber
const ticker$ = new Observable<number>((subscriber) => {
  let count = 0;
  const id = setInterval(() => subscriber.next(count++), 1000);

  // teardown logic runs on unsubscribe
  return () => clearInterval(id);
});

const subscription = ticker$.subscribe((value) => console.log(value));
// later, to stop and clean up:
subscription.unsubscribe();

Once you have internalized the structure of this subscribe/unsubscribe pattern, you immediately recognize the parallel to the cleanup function of useEffect. That is no coincidence but the actual reason why the integration is so straightforward.

The first sensible case: debouncing input#

The classic example is a search field. Firing an HTTP request on every keystroke is wasteful – the user types “React,” and six requests are already on their way, five of which are outdated immediately. The naive React solution cobbles together a setTimeout with clearTimeout in the effect. That works, but it quickly becomes confusing as soon as more than just debouncing comes into play.

With RxJS, debouncing becomes a single declarative operator. debounceTime(300) only emits a value once no new value has followed for 300 milliseconds. I feed the input in through a Subject – a Subject is both an Observable and an Observer, so I can call next() in the onChange handler and subscribe to the pipeline at the other end.

import { useEffect, useRef, useState } from 'react';
import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

function SearchField() {
  const query$ = useRef(new Subject<string>()).current;
  const [debounced, setDebounced] = useState('');

  useEffect(() => {
    const subscription = query$
      .pipe(debounceTime(300), distinctUntilChanged())
      .subscribe(setDebounced);

    return () => subscription.unsubscribe();
  }, [query$]);

  return (
    <input
      type="search"
      onChange={(event) => query$.next(event.target.value)}
      placeholder="Enter search term"
    />
  );
}

Two details regularly get lost in code reviews. I create the Subject with useRef so that it stays stable across re-renders – if I created it anew in the render body, every render would have its own Subject, and the connection between handler and pipeline would break. And distinctUntilChanged() filters out identical consecutive values so that a focus change without a text change does not trigger a new run.

The case where RxJS really shines: autocomplete with switchMap#

Debouncing alone does not justify RxJS yet – you can do that with a timeout too. What carries RxJS is discarding outdated requests. This is exactly where the real race condition of an autocomplete lies: I type “re,” and a request goes out. I type “rea,” and a second request goes out. If the response to “re” now arrives after the response to “rea,” the outdated result overwrites the current one. The UI shows hits for a search term that is no longer in the field at all.

switchMap solves this by construction. The operator subscribes to the inner observable – here the HTTP request – and cancels the previous inner subscription as soon as a new value comes from the outside. Combined with fromFetch and its AbortController, the outdated request is not just ignored but actually aborted.

import { useEffect, useRef, useState } from 'react';
import { Subject } from 'rxjs';
import { fromFetch } from 'rxjs/fetch';
import {
  debounceTime,
  distinctUntilChanged,
  filter,
  switchMap,
} from 'rxjs/operators';

type Hit = { id: string; label: string };

function Autocomplete() {
  const query$ = useRef(new Subject<string>()).current;
  const [results, setResults] = useState<Hit[]>([]);

  useEffect(() => {
    const subscription = query$
      .pipe(
        debounceTime(300),
        distinctUntilChanged(),
        filter((term) => term.length > 1),
        switchMap((term) =>
          fromFetch(`/api/search?q=${encodeURIComponent(term)}`).pipe(
            switchMap((response) => response.json() as Promise<Hit[]>),
          ),
        ),
      )
      .subscribe(setResults);

    return () => subscription.unsubscribe();
  }, [query$]);

  return (
    <div>
      <input onChange={(event) => query$.next(event.target.value)} />
      <ul>
        {results.map((hit) => (
          <li key={hit.id}>{hit.label}</li>
        ))}
      </ul>
    </div>
  );
}

The decisive difference hinges on a single operator name. If you write mergeMap here out of habit, all requests keep running in parallel, and the race condition described above is back. For “only the last input counts,” switchMap is the right choice. The difference becomes tangible if you deliberately build the pipeline with mergeMap once and run it against an artificially slowed-down API: the outdated hits then visibly flash up in the list before the current result replaces them.

The following diagram shows the data flow of the pipeline from input to re-render.

flowchart LR
  A["Input event<br/>onChange"] --> B["Subject.next(term)"]
  B --> C["debounceTime(300)<br/>wait for a quiet period"]
  C --> D["distinctUntilChanged<br/>filter duplicates"]
  D --> E["switchMap<br/>discard old request"]
  E --> F["subscribe<br/>setResults"]
  F --> G["React re-render"]

The cancellation semantics of switchMap are important because they are the core of the whole thing. The second diagram shows them as a sequence: the input “rea” cancels the still open inner stream of “re,” so that only the response to the last input lands in the state.

sequenceDiagram
  participant U as User
  participant P as Pipeline (switchMap)
  participant A as API
  U->>P: Input "re"
  P->>A: Request "re"
  U->>P: Input "rea"
  Note over P: switchMap cancels<br/>inner stream "re"
  P--xA: Request "re" aborted
  P->>A: Request "rea"
  A-->>P: Response "rea"
  P->>U: setResults (only last response)

Continuous streams: WebSockets and events#

The third case where RxJS pays off is sources that do not deliver a single result but keep emitting over time. WebSockets are the obvious example. With webSocket from rxjs/webSocket, RxJS comes with a bidirectional wrapper that is both an Observable and an Observer – I can subscribe to incoming messages and send my own via next(). The detail that is worth its weight in gold here: unsubscribe() closes the connection cleanly.

import { useEffect, useState } from 'react';
import { webSocket } from 'rxjs/webSocket';

type Message = { id: string; text: string };

function LiveFeed() {
  const [messages, setMessages] = useState<Message[]>([]);

  useEffect(() => {
    const socket$ = webSocket<Message>('wss://example.com/feed');

    const subscription = socket$.subscribe((message) =>
      setMessages((prev) => [...prev, message]),
    );

    // unsubscribe closes the underlying socket
    return () => subscription.unsubscribe();
  }, []);

  return (
    <ul>
      {messages.map((message) => (
        <li key={message.id}>{message.text}</li>
      ))}
    </ul>
  );
}

I describe the basics behind such message streams in RxJS: Push and Pull. Bidirectional channels do not change anything about this model: sending and receiving remain two separate streams.

A variant with fromEvent belongs here too, because it reveals a stumbling point. fromEvent attaches to a real DOM node, not to React’s synthetic event system. So you need a ref, and it is only set after mount:

import { useEffect, useRef, useState } from 'react';
import { fromEvent } from 'rxjs';
import { map, debounceTime } from 'rxjs/operators';

function ScrollTracker() {
  const boxRef = useRef<HTMLDivElement>(null);
  const [position, setPosition] = useState(0);

  useEffect(() => {
    const node = boxRef.current;
    if (!node) return;

    const subscription = fromEvent(node, 'scroll')
      .pipe(
        map((event) => (event.target as HTMLElement).scrollTop),
        debounceTime(50),
      )
      .subscribe(setPosition);

    return () => subscription.unsubscribe();
  }, []);

  return <div ref={boxRef}>{/* scrollable content */}</div>;
}

The pitfall that gets everyone once: a missing unsubscribe#

When an RxJS React component inexplicably eats memory or throws a “setState on an unmounted component” warning, the cause is almost always the same: the cleanup function is missing or does not release the subscription. Without unsubscribe(), the stream keeps running after unmount. The event listener stays attached, the timer keeps ticking, the WebSocket stays open – and every emitted value calls a setState on a component that no longer exists.

// Wrong: no cleanup, the stream keeps running after unmount
useEffect(() => {
  interval(1000).subscribe((n) => setTick(n)); // memory leak
}, []);

// Right: keep the subscription and release it in cleanup
useEffect(() => {
  const subscription = interval(1000).subscribe((n) => setTick(n));
  return () => subscription.unsubscribe();
}, []);

The second related mistake is more subtle: building the pipeline in the render body instead of in the effect. A fromEvent(...).pipe(...) that is created anew on every render produces duplicate listeners and duplicate subscriptions. The order that works reliably: keep the source stable (via useRef or outside the component), set up the subscription in the effect, tear it down in the cleanup, and maintain the dependency array carefully.

As a side note for 2022: with useSyncExternalStore, React 18 brings a mechanism for binding cleanly to external stores – including RxJS-based ones. For the cases shown here, though, the useEffect route is entirely sufficient, and I would only reach for useSyncExternalStore when a store really lives outside the component and is used from several places.

When RxJS pays off – and when it does not#

The most common wrong decision is pulling RxJS in everywhere. Two short lists help you avoid it.

RxJS pays off when:

  • input has to be debounced or throttled over time before an expensive effect runs.
  • outdated asynchronous results should be actively discarded (autocomplete, competing requests) – the core case for switchMap.
  • continuous streams such as WebSockets, server-sent events or timers are processed.
  • several event and time sources have to be combined, merged or coordinated in time.

RxJS does not pay off when:

  • it is about simple local component state – that is what useState and useReducer are for.
  • a single request is loaded on mount; a fetch with AbortController in the effect is enough, or you reach for a data-fetching library.
  • the team has not mastered RxJS and the requirement contains no real asynchronous coordination – then the learning curve does not pay off.

This separation is the actual core of the post. RxJS is not a replacement for React’s state model but a complement for a narrow but important slice: coordinating asynchronous events over time. If you use observables deliberately in these few places and stick with React’s built-in tools everywhere else, you get both: declarative streams where they solve real problems, and lean components in the rest of the application. And if you consistently call unsubscribe() in the cleanup, you avoid the one mistake that otherwise reliably comes back.

Further reading#

Revised and translated from German with the help of AI.