almost 8 years ago

Julien Phalip gave a great talk at DjangoCon 2015, he introduced three ways to hydrate (i.e. load initial data into React component on first page load) React app with data, I am going to quote him directly from the slides and add my own comments.

  1. Conventional Method: Client fetches data via Ajax after initial page load.

    Load the data via ajax after initial page load.

  2. Less conventional method: Server serializes data as global Javascript variable in the inital HTML payload (see Instagram).

    Let the server load the data first, then put it into a global Javascript variable which is embed inside the returned HTML page.

    In the linked Github project (which is a Django project), the server fetches from the database to get all of the data. Then, it converts the data from Python object to json format and embed the data in the returned HTML page.

  3. Server side rendering: Let the server render the output HTML with data and send it to the client.

    This one is a little bit involved. Django would pass the data from DB along with the React component to python-react for rendering.

    python-react is a piece of code that runs on a simple Node HTTP server and what it does is receiving the react component along with data via a POST request and returns the rendered HTML back. (The pyton-react server runs on the same server as your Django project.)

So which method to use then?

We can use the number of round trips and the rendering speed as metrics for the judgement.

Method 1

Round trips: The inital page request is one round trip, and the following ajax request is another one. So two round trips.

Rendering time: Server rendering is usually faster then client rendering, but if the amount of data gets rendered is not a lot then this time can be considered negligible. In this case, the rednering happens on the client side. Let's assume the amount of data need to be rendered is small and doesn't impact the user experience, then it is negligible.

Method 2

Round trips: Only one round trip

Rendering time: Negligible as aforementioned.

Method 3

Round trips: Only one round trip

Rendering time: If it is negligible on the client side then it is probably negligible on the server side.

It seems that Method 2 & 3 are equally fast. The differences between them are:

  • Method 2 renders on the client side and Method 3 renders on the server side.
  • Method 3 requires extra setup during development and deployment. Also, the more moving pieces there are, the more likely it breaks and takes longer to debug.


Without hard data to prove, here is just my speculation: Use Method 2 most of the time and only Method 3 if you think rendering on the client side is going to be slow and impact the user experience.

← Converting React project from ES5 to ES6 Understanding the Basics of Webpack →
comments powered by Disqus