crimx / observable-hooks

⚛️☯️💪 React hooks for RxJS Observables. Concurrent mode safe.
https://observable-hooks.js.org
MIT License
1.03k stars 44 forks source link
concurrent-mode react-rxjs react-rxjs-hooks react-rxjs-observable rxjs rxjs-hooks rxjs-observables suspense

observable-hooks

Docs npm-version Build Status Coverage Status

logo

Concurrent mode compatible React hooks for RxJS Observables. Simple, flexible, testable and performant.

Installation

pnpm add observable-hooks

Why?

React added hooks for reusing stateful logic.

Observable is a powerful way to encapsulate both sync and async logic.

Testing Observables is also way easier than testing other async implementations.

With observable-hooks we can create rich reusable Components with ease.

What It Is Not

This library is not for replacing state management tools like Redux but to reduce the need of dumping everything into global state.

Using this library does not mean you have to turn everything observable which is not encouraged. It plays well side by side with other hooks. Use it only on places where it's needed.

At First Glance

import * as React from "react";
import { useObservableState } from "observable-hooks";
import { timer } from "rxjs";
import { switchMap, mapTo, startWith } from "rxjs/operators";

const App = () => {
  const [isTyping, updateIsTyping] = useObservableState(
    transformTypingStatus,
    false
  );

  return (
    <div>
      <input type="text" onKeyDown={updateIsTyping} />
      <p>{isTyping ? "Good you are typing." : "Why stop typing?"}</p>
    </div>
  );
};

// Logic is pure and can be tested like Epic in redux-observable
function transformTypingStatus(event$) {
  return event$.pipe(
    switchMap(() => timer(1000).pipe(mapTo(false), startWith(true)))
  );
}

Usage

Read the docs at https://observable-hooks.js.org or ./docs.

Examples are in here. Play on CodeSandbox:

Note that there are also some useful utilities for common use cases to reduce garbage collection.

Developing

Install dependencies:

pnpm i

Run tests:

pnpm test

Lint code:

pnpm lint