React-Performance-Optimization.png
sohan.png Sohan Manju
6 min read Jan 10, 2022

Performance Optimization for React

To understand how a web page is rendered into the browser, let’s first look at the pixel pipeline. There are 5 phases in rendering a web page.

Page Pipeline
  • Javascript: It is used to introduce logic in a web page like manipulating the DOM, facilitating user interaction, and listening for browser events. Any Javascript on a web page typically has to be loaded, parsed, and executed. If the amount of Javascript accumulating is not kept in check, this process can prove to be expensive with respect to performance.
  • Style Calculations: This step deals with applying CSS rules to the corresponding elements based on the selectors. When the rules are assigned they are applied to the elements and the styles for each element are calculated.
  • Layout: After knowing what rules are to be applied now it needs to take into consideration the space that each element will be occupying and where it will be placed on the screen. This can have a real impact on performance as each element affects the position of the other elements and child elements can also be affected by parent container elements.
  • Paint: The process of drawing the pixels on the screen to form all the content. Drawing out text, colors, images, lines, etc. It involves drawing on multiple layers and basically rasterizing the content
  • Compositing: Placing the painted layers in the correct order so that all the content overlaps as intended is called compositing.

The key metrics that pagespeed utilizes for benchmarking a webpage are as follows:

  • The First Contentful Paint (FCP) metric measures the time from when the page starts loading to when any part of the page’s content is rendered on the screen. For this metric, “content” refers to text, images (including background images), <svg> elements, or non-white <canvas> elements. In the example below we see that the first bit of content starts loading close to the 3-second mark (2841 ms precisely) when simulated on a 4G connection. In this case, at that point in time, it would also be the Largest Contentful Paint which we will see next.
FCP.gif
  • The Largest Contentful Paint (LCP) metric reports the render time of the largest image or text block visible within the viewport, relative to when the page first started loading.
  • Cumulative Layout Shift (CLS) is a measure of the largest burst of layout shift scores for every unexpected layout shift that occurs during the entire lifespan of a page. The GIF below shows how certain elements move from their initial position (Dotted Lines) to their final position upon loading.
cls.gif

To start with Pagespeed Scores aren’t usually a direct measure of how a user experiences a website, but it’s a good practice to optimize nonetheless. Here’s what Page Speed Insights might tell you to improve on, let’s take an example and see what are the improvements suggested. Ideally, FCP should be within 1.8 seconds and if it’s beyond 3 seconds then your webpage is considered slow.

Next-Gen-Format.png Efficient-Encode.png Defer-Images.png
  • Serving Images in efficient formats and deferring offscreen images: For images just use JPEG with a good image codec like HEIC. For further improvements, one can use next gen formats like AVIC and WEBP images. Any images which aren’t visible on opening a page and needs to be scrolled to be seen need not be loaded immediately, they can be lazy loaded in order to be non render blocking.
Server-Respone-Time.png
  • Reduce Initial Server Response times: First Contentful Paint is dependent on a bunch of other factors, i.e FCP = TTFB + Content Load Time + Render Time. TTFB (Time to first byte) is the time taken by the browser to receive the first byte. This can again be improved by choosing a better CDN or a Fast Hosting Provider. A good idea might be to rely on Static Site Generation whenever possible. If you need to use Server Side Rendering, make sure you have caching enabled so that requests don’t hit the origin more often than is desirable.
Reduce-Unused-Javascript.png
  • Minimize the amount of Javascript: JavaScript is a powerful language that can do some complex things, but there might be opportunities to accomplish the same task using other methods. An example where people commonly use Javascript wastefully is for animations, see if you can do it in CSS instead. For simple form input validation, you can use simple HTML input types. In the case where you do need to use Javascript, you can think of performing most of the work on the server-side (via SSR for example) and sending only a small amount of Javascript to the client for hydration, saving your viewers from performing expensive computation on their browsers. You can try to shrink that client-side Javascript even further by using Preact instead of React which can contribute to making your client-side bundle size smaller while not compromising on existing functionality.
Render-Block.png
  • Eliminate Render-Blocking Resources: So, when the user requests for a webpage, the browser would’ve received the HTML content since it is very light compared to the other content it has to receive, but will still be waiting for all the other resources it thinks is critical to be loaded before rendering the page. As a result, they’re called render-blocking resources. You can try to minimize those resources (they might typically be CSS and JS resources), or you can try to defer some of those resources so that the browser knows that they are not critical and won’t hold up rendering while they load.
  • Critical CSS: When CSS required for a page is loaded via an external stylesheet or via JS hydration, there is a momentary flash of un-styled content as the page loads. This effect is more prominent for users with slow network conditions, like a person on the train who’s viewing your site on their budget phone with one bar of LTE network. For any public website, this audience actually represents the majority of traffic so ruining their user experience in this manner is not a good thing. Critical CSS is a technique that extracts the CSS for above-the-fold content in order to render content to the user as fast as possible. If CSS files are big, or network conditions are poor, requests for CSS files can significantly increase the time it takes for a web page to render. Above-the-fold is all the content a viewer sees on page load, before scrolling. There is no universally defined pixel height of what is considered above the fold content since there is a myriad of devices and screen sizes. It all depends on the general content that appears and should be appropriately estimated. Using critical CSS makes sure that there’s not a lot of layout shift involved as a whole and improves your CLS (Cumulative Layout Shift) scores by a long shot.

You can incorporate these strategies to improve Pagespeed Scores and Website Performance in general significantly. But be mindful about diminishing returns as it’s easy to go from 40 to 90 Pagespeed score but hard to go the extra mile from 90 to 95.

References

Pixel Pipeline: https://developers.google.com/web/fundamentals/performance/rendering

Application Modernization Icon

Explore limitless possibilities with AntStack's frontend development capabilities. Empowering your business to achieve your most audacious goals. Build better.

Talk to us

Author(s)

Tags

Your Digital Journey deserves a great story.

Build one with us.

Recommended Blogs

Cookies Icon

These cookies are used to collect information about how you interact with this website and allow us to remember you. We use this information in order to improve and customize your browsing experience and for analytics and metrics about our visitors on this website.

If you decline, your information won’t be tracked when you visit this website. A single cookie will be used in your browser to remember your preference not to be tracked.

Talk to us