react-use-observable-statedeprecated

React hook to interact with any kind of observable.

Usage no npm install needed!

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

README

👀 React use observable state npm ko-fi

React hook that consumes any kind of observable via useState.

Installation

npm install react-use-observable-state
# or
yarn add react-use-observable-state

Definition

declare type UseObservable = <T>(obs$: Observable<T>, defaultVal: T, fn?: UseObservableFn<T>) => [T, UseObservableFn<T>];
declare type UseObservableFn<T> = (val: T) => void;

declare const useObservable: UseObservable;

Usage

The observable can be any kind of object with a subscribe and a next property. For eg with RxJS:

counter/service.ts:

import {BehaviorSubject} from "rxjs";

export const counter$ = new BehaviorSubject(0);
export function incrementCounter() {
  counter$.next(count => count + 1);
}

counter/component.tsx:

import React from "react"
import {useObservable} from "react-use-observable-state";

import {counter$, incrementCounter} from "./service"

const MyComponent: FC = () => {
  const [count] = useObservable(counter$, counter$.value);
  return <button onClick={incrementCounter}>{count}</button>;
}

Development

git clone https://github.com/soywod/react-use-observable-state.git
cd react-use-observable-state
yarn

Tests

yarn test