React, server side rendering, and a cool data embedding technique
I've been spending some time going through the React docs and examples for some work on a side project.
What is React? From their website:
The React devs have some killer ideas about how to render web pages using something they call a Virtual DOM. Also from React's website:
React uses a virtual DOM diff implementation for ultra-high performance. It can also render on the server using Node.js — no heavy browser DOM required.
Some people who've been experimenting with React has shown dramatic client-side rendering performance improvements - 2-4x faster in the average case, up to 30-40x in certain cases.
The Virtual DOM implementation would be enough for most people to switch over to trying out React, but I think the killer feature of React isn't the blazing client-side performance - it's the ability to server-side render.
It's well known that server-side rendering can reduce page load times. Twitter claimed to reduce page loads times to 1/5th of what they had been by server side rendering.
1/5th * (2x as fast) == Blazing Rendering
(Especially in low-power devices like phones)
So how do you server side render with React?
The client makes a request for a page.
On the server, you:
- You grab whatever data is appropriate for the request
- You pass that data into some React components, generating HTML
- You embed the data in a page to send to the client
- You embed the generated HTML in a page to send to the client
- You add a script block to include all the needed JS in the page to glue to all together
- You send the client back the html with the data / generated HTML / react JS code.
A good example of this flow here.
My favorite part of this example - and a cool way to embed some code - are these lines of code:
That embedding code - adding data to a DOM element for a particular component - is a pretty cool way to get the data you need client-side.