Skip to content

Instantly share code, notes, and snippets.

@ezekielchentnik
Last active January 6, 2021 05:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezekielchentnik/c924079e4b4896158b54ee470b1c2e2b to your computer and use it in GitHub Desktop.
Save ezekielchentnik/c924079e4b4896158b54ee470b1c2e2b to your computer and use it in GitHub Desktop.
react rxjs hook useStream
import React, { useState, useEffect, createContext, useContext } from "react";
import { render } from "react-dom";
import { BehaviorSubject, isObservable } from "rxjs";
const Context = createContext();
const Provider = Context.Provider;
const useStream = initialState => {
let source = isObservable(initialState)
? initialState
: new BehaviorSubject(initialState);
let currentState;
source.subscribe(val => (currentState = val)).unsubscribe();
let [value, setValue] = useState(currentState);
let [subject] = useState(source);
useEffect(() => {
let sub = subject.subscribe(setValue);
return () => sub.unsubscribe();
}, []);
return [value, subject.next.bind(subject)];
};
const Stream = () => {
const source = useContext(Context);
const [value, next] = useStream(source);
return (
<div>
<div>{value}</div>
<button onClick={() => next(value + 1)}>+</button>
<button onClick={() => next(value - 1)}>-</button>
</div>
);
};
const App = () => (
<Provider value={new BehaviorSubject(0)}>
<Stream />
<Provider value={new BehaviorSubject(5)}>
<Stream />
</Provider>
</Provider>
);
const root = document.getElementById("root");
render(<App />, root);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment