Getting Started

Installation

React-RxJS is published in npm as @react-rxjs/core

npm i rxjs @react-rxjs/core

or using yarn

yarn add rxjs @react-rxjs/core

Create a hook from an observable

@react-rxjs/core exports a function called bind which is used to connect a stream to a hook.

import { Subject } from "rxjs"
import { startWith } from "rxjs/operators"
import { bind } from "@react-rxjs/core"
const textSubject = new Subject()
const setText = (newText) => textSubject.next(newText)
const [useText, text$] = bind(textSubject.pipe(startWith("")))
function TextInput() {
const text = useText()
return (
<div>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<br />
Echo: {text}
</div>
)
}

bind returns a tuple that contains the hook, plus the underlying shared observable so it can be used by other streams:

import { map } from "rxjs/operators"
import { bind, Subscribe } from "@react-rxjs/core"
// Previously...
// const [useText, text$] = bind(...);
const [useCharCount, charCount$] = bind(text$.pipe(map((text) => text.length)))
function CharacterCount() {
const count = useCharCount()
return <>Character Count: {count}</>
}

Something to note is that a subscription on the underlying observable must be present before the hook is executed. We can use Subscribe to help us with it:

function CharacterCounter() {
return (
<div>
<Subscribe source$={charCount$}>
<TextInput />
<CharacterCount />
</Subscribe>
</div>
)
}

This is shown as:

Next steps

We strongly recommend reading through core concepts to understand the mindset of this library.