How to render asynchronously initialized components on the server


I'm relatively new to ReactJS and have been seduced by the ease of implementing server-side rendering to reduce "time to first tweet". I'm running a Node-Express-React stack which pre-renders the markup on the server using React's renderComponentToString.

It works fine when the components can be rendered synchronously, however I'm struggling when it comes to implementing ajax-populated components (however this applies to any asynchronous operation during the initialization of the component, e.g. websocket).

Take the example from the React website:

componentDidMount: function() {
 $.get(this.props.source, function(result) {
  var lastGist = result[0];
    username: lastGist.user.login,
    lastGistUrl: lastGist.html_url

It won't work on the server, since componentDidMount is never triggered when using renderComponentToString. This simple case can be worked around by using the same HTTP request wrapper on the client and on the server (instead of using jQuery's $.get), and by pre-fetching the data before instantiating the component and passing it as a prop.

However, in an actual, complex app, asynchronous dependencies can get very complicated and pre-fetching doesn't really fit the descendant approach of building React structures. How can I implement an asynchronous initialization pattern in React that can be rendered on the server without actually mounting anything (i.e. no DOM emulation a la PhantomJS, which is the whole point of using renderComponentToString) ?


you can check out react-nexus ( which helps you declare all your async dependencies ahead of time.

but I realize that react-nexus is your own answer to this problem so you probably already found it !

This video can help you solving your question :)
By: admin