• Stars
    star
    100
  • Rank 332,823 (Top 7 %)
  • Language
    JavaScript
  • Created over 7 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Prepare you app state for async server-side rendering and more!

react-prepare

react-prepare allows you to have you deeply nested components with asynchronous dependencies, and have everything just work with server-side rendering.

The typical use-case is when a deeply-nested component needs to have a resource fetched from a remote HTTP server, such as GraphQL or REST API. Since renderToString is synchronous, when you call it on your app, this component won't render correctly.

One solution is to have a central router at the root of your application that knows exactly what data needs to be fetched before rendering. But this solution doesn't fit the component-based architecture of a typical React app. You want to declare data dependencies at the component level, much like your declare your props.

This is exactly what react-prepare does: it allows you to declare asynchronous dependencies at the component level, and make them work fine with server-side rendering as well as client-side rendering.

react-prepare is agnostic and can be used vanilla, but it comes with a tiny helper that makes it extremely easy to use along redux and react-redux (see examples below).

Example with react-redux

Let's assume you have defined an async action creator fetchTodoItems(userName) which performs HTTP request to your server to retrieve the todo items for a given user and stores the result in your redux state.

Your TodoList component definition would look like this:

import { dispatched } from 'react-prepare';
import { connect } from 'react-redux';
import { compose } from 'redux';

import { fetchTodoItems } from './actions';

const enhance = compose(
  dispatched(({ userName }, dispatch) => dispatch(fetchTodoItems(userName))),
  connect(({ todoItems }) => ({ items: todoItems }),
);

const TodoList = ({ items }) => <ul>{items.map((item, key) =>
  <li key={key}>{item}</li>
</ul>}</ul>;

export default enhance(TodoList);

And your server-side rendering code would look like this:

import { renderToString } from 'react-dom/server';
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { Provider } from 'react-redux';
import prepare from 'react-prepare';

import reducer from './reducer';

async function serverSideRender(userName) {
  const store = createStore(reducer, applyMiddleware(thunkMiddleware));
  const app = <Provider store={store}>
    <TodoList userName={userName} />
  </Provider>;
  await prepare(app);
  return {
    html: renderToString(app),
    state: store.getState(),
  };
}

Your client could re-use the data fetched during server-side rendering directly, eg. assuming your injected it in window.__APP_STATE__:

const store = createStore(reducer, JSON.parse(window.__APP_STATE__));
render(<Provider store={store}>
  <TodoList userName={userName} />
</Provider>, document.getElementById('app'));

For a complete example of a fully-functional app using react-prepare in conjunction with redux, see the react-prepare-todo repository.

API

dispatched(sideEffect: async(props, dispatch), opts)(Component)

Helper to use prepared more simply if your side effects consists mostly of dispatching redux actions.

In the body of the sideEffect function, you can use the dispatch function to dispatch redux actions, typically requesting data from an asynchronous source (API server, etc.). For example, let's assume you have defined an async action creator fetchTodoItems(userName) that fetches the todo-items from a REST API, and that you are defining a component with a userName prop. To decorate your component, your code would look like:

class TodoItems extends React.PureComponent { ... }

const DispatchedTodoItems = dispatched(
  ({ userName }, dispatch) => dispatch(fetchTodoItems(userName))
)(TodoItems);

The decorated component will have the following behavior:

  • when server-side rendered using prepare, sideEffect will be run and awaited before the component is rendered; if sideEffect throws, prepare will also throw.
  • when client-side rendered, sideEffect will be called on componentDidMount and componentWillReceiveProps.

opts is an optional configuration object passed directly to the underlying prepared decorator (see below).

prepared(sideEffect: async(props, context), opts)(Component)

Decorates Component so that when prepare is called, sideEffect is called (and awaited) before continuing the rendering traversal.

Available opts is an optional configuration object:

  • opts.pure (default: true): the decorated component extends PureComponent instead of Component.
  • opts.componentDidMount (default: true): on the client, sideEffect is called when the component is mounted.
  • opts.componentWillReceiveProps (default: true): on the client, sideEffect is called again whenever the component receive props.

async prepare(Element)

Recursively traverses the element rendering tree and awaits the side effects of components decorated with prepared (or dispatched). It should be used (and await-ed) before calling renderToString on the server. If any of the side effects throws, prepare will also throw.

Notes

react-prepare tries hard to avoid object keys conflicts, but since React isn't very friendly with Symbol, it uses a special key for its internal use. The single polluted key in the components key namespace is @__REACT_PREPARE__@, which shouldn't be an issue.

More Repositories

1

react-armor

Protect your DOM from third-party tampering.
JavaScript
636
star
2

coding-styles

My coding styles.
398
star
3

react-animate

React animation mixin.
JavaScript
271
star
4

nexus-flux

Streamlined Flux abstract interface suitable for a variety of backends.
JavaScript
241
star
5

remutable

Like Immutable, but actually Mutable with diffs and versions.
JavaScript
222
star
6

fastify-zod

Zod integration with Fastify
TypeScript
188
star
7

directus-typescript-gen

JavaScript
84
star
8

react-traverse

React Components Magic
JavaScript
70
star
9

nexus-flux-socket.io

socket.io adapter for Nexus Flux, implementing Flux over the Wire.
JavaScript
53
star
10

react-rails-starterkit

Starter repository for React on Rails. Fork it!
JavaScript
47
star
11

typed-assert

A typesafe TS assertion library
TypeScript
47
star
12

react-css

Converts plain CSS into (optionally auto-prefixed) React-style properties map.
JavaScript
35
star
13

es6-starterkit

The future is today!
JavaScript
33
star
14

useless

Useless React hooks
TypeScript
32
star
15

react-query

React Virtual DOM querying made easy.
JavaScript
30
star
16

react-statics-styles

Declarative styles in React components with support for pre- and post-processing.
JavaScript
26
star
17

react-nexus-chat

Demo chat app using React Nexus.
CSS
18
star
18

react-styling-demo

Demos for react-animate, react-css and other React styling demos.
JavaScript
17
star
19

react-defer

React Mixin for dealing with defers/timeouts/intervals/requestAnimationFrame with less boilerplate.
JavaScript
16
star
20

react-nexus-starterkit

React Nexus Starterkit Project. Clone/fork, hack, deploy!
JavaScript
12
star
21

node-async-context

Node Async Context Monitoring & Isolation
JavaScript
8
star
22

immutable-request

Isomorphic cacheable and cancellable HTTP request than return Promise for Immutable.Map.
JavaScript
8
star
23

lifespan

Unifying callbacks removals.
JavaScript
7
star
24

typed-jest-expect

Elegant jest.expect typings for a more civilized age
TypeScript
7
star
25

isomorphic-router

Tiny, lightweight isomorphic router.
JavaScript
6
star
26

gulp-react-statics-styles

Gulp task for react-statics-styles.
JavaScript
5
star
27

tween-interpolate

Extra lightweight generic and CSS values interpolators and tweens.
JavaScript
5
star
28

typed-react-openapi

Idiomatic, strongly typed React OpenAPI integration
TypeScript
5
star
29

hypernode

Ideas and prototypes for Hypernode, a scalable, distributed JS node environment.
JavaScript
4
star
30

react-transform-props

React Component decorator for transforming props
JavaScript
4
star
31

nexus-uplink-simple-server

Nexus Uplink Simple Server (for Node).
JavaScript
4
star
32

react-nexus-app

React Nexus App skeleton.
JavaScript
4
star
33

nexus-uplink-client

Nexus Uplink Client (isomorphic).
JavaScript
4
star
34

algebraic-effects-experiments

Experiments with algebraic effects
JavaScript
3
star
35

react-esi-poc

JavaScript
3
star
36

typecheck-decorator

Runtime arguments validation as ES7 decorators.
JavaScript
3
star
37

virtual

Userland virtual methods and abstract classes for ES6.
JavaScript
3
star
38

typed-result

A liberal reinterpretation of the Result type for TypeScript
TypeScript
3
star
39

lisa-db

TypeScript
2
star
40

react-maybe-state

React Mixin for maybe getting state (defaulting to null).
JavaScript
2
star
41

otter-den

TypeScript
2
star
42

snippets

Snippets of code to copy/paste.
TypeScript
2
star
43

react-ml

JavaScript
2
star
44

http-exceptions

HTTP Exceptions with err codes.
JavaScript
2
star
45

lisa-prototype

TypeScript
2
star
46

react-nexus-todomvc

React Nexus obligatory TodoMVC. (WORK IN PROGRESS)
JavaScript
2
star
47

react-lambda

Higher order and functional utilies for manipulating React components
JavaScript
2
star
48

react-http

Universal HTTP client for use in React applications.
JavaScript
2
star
49

rotenberg.io

My homepage
Lua
1
star
50

RktTools

Wow RktTools addon
Lua
1
star
51

backend-starterkit

Node Koa/postgresql backend starterkit
JavaScript
1
star
52

typed-utilities

Strongly typed general purpose utilities
TypeScript
1
star
53

wow-scripts

Lua
1
star
54

typed-ref

TypeScript
1
star
55

wow-workbench

TypeScript
1
star
56

react-identicon

React Component for Gravatar identicons.
JavaScript
1
star
57

mindstorms-utilities

Utilities for Lego Mindstorms
JavaScript
1
star
58

netlify-cms-toolkit

Tools and utilities for Netlify CMS
TypeScript
1
star
59

nexus-events

Yet Another EventEmitter. Sane callbacks removals.
JavaScript
1
star
60

lodash-next

An extension of lodash for next level js.
JavaScript
1
star
61

remembrall-pi

Python
1
star
62

mindlogger-node

TypeScript
1
star
63

nexus-flux-rest

Nexus Flux backend using plain HTTP requests (REST-like).
JavaScript
1
star
64

workbench

JavaScript
1
star
65

where-did-i-put-it

One button to find them all
TypeScript
1
star
66

node-pg-container

Postgres containers for Node
TypeScript
1
star
67

react-ml-editor

ReactML editor with live preview and suggest-completion.
JavaScript
1
star