Render Caching for React

Server Side Rendering (SSR) is a very useful technique that makes web apps appear faster. The initial HTML is displayed before the JavaScript is parsed and, while the user is deciding what to tap on, our handlers are ready.

Server side rendering in React requires additional work to setup and has server costs. Furthermore, if your server team cannot have JavaScript running on your servers, you are stuck. It significantly complicates the hydrate conditionally. Event handlers will become functional once this code hits but the DOM should not change.

import {render, hydrate} from "react-dom" if (window.hasRestoredState) { hydrate(<MyPage />, document.getElementById('content'));
} else { render(<MyPage />, document.getElementById('content'));
}

Step 6: Go Async all the way

Turn your script tags from sync to async/defer for loading the JavaScript files. This is another key step to ensure a smooth loading and rendering experience on the front end.

That’s it! Reload the page to see the boost in performance.

Measuring improvement

OK, so you did all that work and now you want to know just how performant your site is. You’re going to want to benchmark the improvements.

Render Caching shines in situations where you have multiple server calls before you know what to render. On script-heavy pages, JavaScript can actually take a lot of time to parse.

You can measure the load performance in the Performance tab in Chrome’s DevTools.

Measuring rendering in the Performance tab of Chrome’s DevTools

Ideally, you’d use a guest profile so that your browser extensions won’t interfere with the measurements. You should see a significant improvement on reload. In the screenshot above, we a sample app with an async data.json fetch call that is performed before calling ReactDOM.hydrate. With Render Caching, the render is complete even before the data is loaded!

Wrapping up

Render Caching is a clever technique to ensure that the perceived speed of re-fetches of the same web page is faster by adding a caching layer to the final HTML and showing them back to the user. Users who visit your site frequently are the ones who stand to benefit the most.

As you can see, we accomplished this with very little code and the performance gains we get in return are huge. Do try this out on your website and post your comments. I’d love to hear whether your site performance sees the same significant boosts that I’ve experienced.

The post Render Caching for React appeared first on CSS-Tricks.