use-observable

Allows dereferencing of Observables using React hooks

Usage no npm install needed!

<script type="module">
  import useObservable from 'https://cdn.skypack.dev/use-observable';
</script>

README

useObservable

Allows dereferencing of Observables (see RxJS) using React hooks.

Install

yarn add use-observable

Use

This package exports a single function useObservable<T>(obs: Observable<T>, defaultValue: T): T.

import React from "react";
import ReactDOM from "react-dom";
import { interval } from "rxjs";
import useObservable from "use-observable";

const intCounter = interval(1000);

const App = () => {
  const [count, setCount] = React.useState(0);
  const obsCount = useObservable(intCounter, 0);

  return (
    <div>
      <div>The observable count is: {obsCount}</div>
      <div>The click counter is: {count}</div>
      <div>The total count is: {obsCount + count}</div>
      <div>
        <button onClick={() => setCount(count + 1)}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
      </div>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));