React observing

Manual subscription

Manual subscription

We recommend our hooks for most use cases, see here.

Overview

The react-observing allows you to manually subscribe to value changes of an observable object.

In some very complex cases, normal hooks may not be enough. To work around the problem you can use the subscribe method available on any observable object.

Definition

interface IObservable<T> {
id: string;
value: T;
subscribe(callback: (val: T) => void): ISubscription;
}

Examples

Counter

In any react component you can use the subscribe of an observable.

1import { useState, useEffect } from 'react'
2import { observe, set } from 'react-observing'
3
4const counterObservable = observe(0)
5
6const App = () => {
7 const [counter, setCounter] = useState(0)
8
9 useEffect(() => {
10 const subscription = counterObservable.subscribe(receivedValue => setCounter(receivedValue))
11
12 return () => subscription.unsubscribe()
13 })
14
15 return (
16 <button onClick={() => set(counter + 1)}>
17 Add +1 in {counter}
18 </button>
19 )
20}
Edit this page on GitHub