Universal Data Retrieval
Learn the basics of popularly used universal data retrieval methods.
We'll cover the following...
Server-side rendering is a synchronous operation and this makes it tricky to preload all the necessary data effectively. Being able to avoid the problems we underlined at the end of the previous section isn’t as straightforward as we might expect.
The root of the problem is that we’re keeping our routing logic within the React application, so, on the server, we can’t know which page we’re actually going to render before we call the renderToString()
method. This is why the server can’t establish whether we need to preload some data for a particular page.
Universal data retrieval is still really a nebulous area in React, and different frameworks or libraries that facilitate React server-side rendering have come up with different solutions to this problem.
As of today, the two patterns that we believe are worth discussing are two-pass rendering and async pages. These two techniques have different ways of figuring out which data needs to be preloaded. In both cases, once the data is fully loaded on the server, the generated HTML page will provide an inline script
block to inject all the data into the global scope (the window
object) so that when the application runs on the browser, the same data already loaded on the server won’t have to be reloaded from the client.
Two-pass rendering
The idea of two-pass rendering is to use the React router static context as a vector to exchange information between React and the server. The illustration below shows us how this works:
The steps of two-pass rendering are as follows: ...