React Bacon.js
React bindings for Bacon.js. Create functional-reactive, universal web apps with ease.
Installation
React Bacon.js requires React 16.8.3 or later and Bacon.js 0.7.59 or later.
npm i -S react-baconjs
Configure the build
Important: The react-baconjs
package is not transpiled! Your project
must transpile it.
See Webpack or Browserify instructions.
What it does
React Bacon.js connects an observable to a component to create a widget.
A widget is a React component whose state is managed by a Bacon.js 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
React Bacon.js is an alternative to React Redux, using Bacon.js as the state manager instead of Redux.
The two libraries have some key differences:
React Redux | React Bacon.js | |
---|---|---|
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 a Bacon.js 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 'react-baconjs';import profileContext from './profile-context'; const ProfileName = <section ="profile__name"> <Inject = = > isLoading name isLoading ? <em> Loading... </em> : name </Inject> </section>; const ProfilePhoto = <section ="profile__photo"> <Inject => isLoading photo <img ="profile__photo-img" = = /> </Inject> </section>; const Profile = <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: Profile context: profileContext { const userId$ = props$; const name$ = hydration ? : userId$; const photo$ = hydration ? : userId$; return // Start with a loading state (which is skipped by Bacon.js when // combineTemplate resolves immediately) ... // ... but skip it if an immediate value isn't required ; };
The general contract of getData(props$, hydration, immediate)
is:
- Return a Bacon.js
Property
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 'react-baconjs';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 a Bacon.js Property
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 Bacon.js.
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> ;}
import combineTemplate constant from 'baconjs';import widget from 'react-baconjs';import Profile from './profile';import fetchName from './streams/fetch-name';import fetchPhoto from './streams/fetch-photo'; name: 'profile' component: Profile { const userId$ = props$; const name$ = hydration ? : userId$; const photo$ = hydration ? : userId$; return // Start with a loading state (which is skipped by Bacon.js when // combineTemplate resolves immediately) ... // ... but skip it if an immediate value isn't required ; };
This saves you from the following additional boilerplate:
// NOTE: Don't do this! const context = React;const component = <Inject => state <Profile /> </Inject>; name: 'profile' context component getData;
However, it means that React is potentially diffing larger chunks of virtual DOM.
Hooks
A custom hook is provided as an alternative to <Inject />
.
// profile.js import React from 'react';import useWidgetState from 'react-baconjs';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 'react-baconjs';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.