There is a lot of information on the web about how to use server-side rendering, or SSR, with React. But the question you'll want to answer first is: should I use it?
Server-side rendering is very cool, and a must-have in certain situations, but it comes with drawbacks.
Before you jump into server-side rendering, consider carefully:
Does server-side rendering make sense for my React app?
Here are three topics to consider when looking at server-side rendering:
Wait, what is SSR?
With SSR, the initial content is generated on the server, so your browser can download a page with HTML content already in place. Updates to the content are still handled in the browser.
Fixing this problem could be the single biggest reason to go for server-side rendering.
Server-side rendering can improve performance in many situations but worsen it in others.
SSR is more work for your server, so your HTTP response will take a little longer to return. A lot longer if your servers are under heavy load.
The size of your HTML will be increased and will take longer to download. For most apps this should be negligible, but could become a factor if your React components contain long lists or tables.
We cannot say performance is better with SSR or performance is worse with SSR. Neither statement would be true in general.
Server-side rendering increases the complexity of an app in a few ways.
windowand other browser-specific APIs exist before using them.
react-routeron the client side, you'll need to rewrite those same routes on your server.
Adding SSR to your site isn't trivial, so don't use it unless you need it for performance or SEO reasons. To find out if those apply to you, read on.
If you would rather not use server-side rendering, here are a couple alternatives:
Place some information inside your mount element. Crawlers will see it, and React will replace it. Like this:
<div id="mount"> This content is searchable. </div>
Don't use SSR just because it's sexy right now - it comes with a cost.
Consider whether or not server-side rendering makes sense for YOUR app, and decide accordingly.
And for help making more of these architectural React decisions in the future, sign up for the Modern JS newsletter!