Universal React RxJS
Create universal web apps with React and RxJS.
Installation
Universal React RxJS requires React 16.8.3 or later and RxJS 6.0.0 or later.
npm i -S universal-react-rxjs
Configure the build
Important: The universal-react-rxjs
package is not transpiled! Your
project must transpile it.
See Webpack or Browserify instructions.
What it does
Universal React RxJS connects an observable to a component to create a widget.
A widget is a React component whose state is managed by an RxJS observable.
Widgets can also be server-side rendered asynchronously, even if they have ancestor widgets and/or descendant widgets.
Server-side rendered widgets can be hydrated, with the initial state provided by the server, so that the browser doesn't have to call any endpoints for the initial render.
Comparison to React Redux
Universal React RxJS is an alternative to React Redux, using RxJS as the state manager instead of Redux.
The two libraries have some key differences:
React Redux | Universal React RxJS | |
---|---|---|
Multiple stores/observables | Discouraged | Unopinionated |
Relationship to component tree | Decoupled | Attached to a component |
Asynchronous state change | Requires third-party libraries | Built-in |
Server-side rendering | No | Yes |
Usage
Create a context to connect an RxJS observable to your React component:
// profile-context.js ; ;
Create your React component hierarchy, connecting your context to it using
<Inject context={yourContext} />
:
// profile.js import React from 'react';import Inject from 'universal-react-rxjs';import profileContext from './profile-context'; { return <section ="profile__name"> <Inject = = > isLoading name isLoading ? <em> Loading... </em> : name </Inject> </section> ;} { return <section ="profile__photo"> <Inject => isLoading photo <img ="profile__photo-img" = = /> </Inject> </section> ;} { return <section ="profile"> <ProfileName /> <ProfilePhoto /> </section> ;}
NOTE: compare
specifies how to skip widget states that are duplicates with
respect to the subset of the state being used. Typically, this is just a list
of the widget state properties being used. However, you can instead specify a
function that compares consecutive widget states for equality.
Define your component's event stream and create a widget:
// profile-widget.js;;;;;;; name: 'profile' component context { const userId$ = props$; const name$ = hydration ? : userId$; const photo$ = hydration ? : userId$; return ; };
The general contract of getData(props$, hydration, immediate)
is:
- Return an RxJS
Observable
that emits objects of the form{state, hydration, data}
where bothstate
andhydration
are objects anddata
is any additional data you want to accumulate during server-side rendering. - If the third parameter (
immediate
) provided togetData
istrue
, the observable is expected to immediately produce an event. - Events must contain
hydration
during server-side rendering. - Events can contain
hydration
and/ordata
client-side, but it will have no effect. - Keep hydration small to keep server-side rendered HTML pages small. Only attach the minimum amount of data required to hydrate widgets without them having to fetch data from APIs.
Somewhere on the server:
import React from 'react';import renderToHtml from 'universal-react-rxjs';import ProfileWidget from './profile-widget'; // Server-side render an HTML page consisting of the profiles from a list of// user IDs. { let maxAge = 60; // Default max-age to 60s // Generate server-side rendered profile of users const htmlArray = await Promise; return maxAge html: `<body></body>` ;}
When renderToHtml
is called, it will call each widget's getData
function,
passing in an RxJS Observable
that emits the widget's props (in this case,
userId
) every time it's rendered. When the stream returned by getData
produces its first event (an object consisting of state
to inject into the
React component and hydration
to attach to the HTML page), the widget's React
component will be rendered with the state
as its props
and the hydration
data will be rendered adjacent to it in the HTML page. The data
property of
the event will be passed to the onData
function specified in renderToHtml
,
if specified at all. It is up to the onData
function to accumulate data
objects as it sees fit, bearing in mind that onData
is called in render
order, which is defined by ReactDOM.renderToString
.
Somewhere on the client:
;; // Hydrate all instances of profile-widget on the page;
When hydrate
is called, it finds all the server-side rendered instances of
the widget in the DOM, reads their attached props
and hydration
data, then
calls getData(props$, hydration, immediate)
, expecting the client to render
the profiles synchronously, without having to load data from APIs.
Bear in mind that widgets are just React components, so you can use them directly in JSX and you don't even need to initially render them on the server. You could even use this library just for connecting to RxJS.
Contextless form
In some situations, context is overkill, because your UI is fairly shallow and
there is not much benefit, if any, to be gained by using a context. And in some
cases, you may be using a component from a third-party library as the
copmonent
parameter. For this reason, context
is optional. If you don't
provide a context
, the state
of the stream returned by getData
will be
fed directly into the component's props (which otherwise doesn't receive props
from widget
).
import React from 'react'; { return <section ="profile"> <section ="profile__name"> isLoading ? <em> Loading... </em> : name </section> <section ="profile__photo"> <img ="profile__photo-img" = = /> </section> </section> ;}
name: 'profile' component: Profile { // Use your imagination... } // context omitted;
This saves you from the following additional boilerplate:
// NOTE: Don't do this! const context = React; { return <Inject => state <Profile /> </Inject> ;} name: 'profile' context component getData;
Hooks
A custom hook is provided as an alternative to <Inject />
.
// profile.js import React from 'react';import useWidgetState from 'universal-react-rxjs';import profileContext from './profile-context'; { const isLoading name photo = ; return <section ="profile"> <section ="profile__name"> isLoading ? <em> Loading... </em> : name </section> <section ="profile__photo"> <img ="profile__photo-img" = = /> </section> </section> ;}
Refs
Refs work as expected. Any ref
passed to a widget will be forwarded to the
underlying component.
{ const profileRef = ; return <ProfileWidget = // = /> ;}
The underlying component must be capable of taking a ref
. Note: Inject
is
incapable of forwarding ref
s.
Support for styled-components
The server-side rendering portion of the above example can be updated as follows:
import React from 'react';import renderToHtml StyledComponentsServerRenderer from 'universal-react-rxjs';import ProfileWidget from './profile-widget'; // Server-side render an HTML page consisting of the profiles from a list of// user IDs. { // Generate server-side rendered profile of users const renderer = ; const htmlArray = await Promise; return `<head></head><body></body>`;}
This uses StyledComponentsServerRenderer
as an alternative renderer, which
uses ServerStyleSheet
from styled-components to gather rendered stylesheets.
Contributing
Contributions are welcome. See CONTRIBUTING.md in this repo for contribution guidelines.