Member-only story
React - Async SSR without NextJS
This article is for those that find React SSR tedious and mildly annoying to use in real world applications. For the people that want a similar application structure as NextJS without all the trouble.
All the code examples are written in Typescript. JavaScript developers should remove the types or consider switching to Typescript. (Check out Parcel if you havenβt)
Problem
By now, you have probably discovered that React SSR is synchronous. Meaning, it is impossible to server render data from a database unless each route is handled on the server using a library like Express, or Koa.
What if you want all your code in one place? What if you want React to handle all the routing and fetching?
The answer is simple. Write a static method that fetches the data asynchronously and call that method on the server before any SSR is started.
Component Structure
Here is what the static method may look like inside the component file. Notice I am using a hook and pulling data from the hook rather than the props. But why?
If you are using React Router, SSR is only good for the first load. Any subsequent page navigation is rendered in the browser. Hence, the component needs to use props provided by the server andβ¦