Invisible Hand of React Performance

Rate this content
Bookmark

Did you know introducing useEffect solved a whole class of performance issues? Did you know <Suspense> was designed to make hydration several times smoother without you even noticing anything? 


React has changed a lot. Many of these changes were driven by a desire for better architecture. But under the hood, each of these changes also pushed us to write faster apps – often, without us even noticing that.


In this talk, let’s look at some rarely known React performance details almost nobody knows about:


- useEffect, and how it’s faster than componentDidMount

- Batching, and how it improved from version 0.4 to 0.12 to 18

- Suspense, and some of the less obvious effects of using it

- and possibly even more

This talk has been presented at React Summit 2024, check out the latest edition of this React Conference.

FAQ

The useEffect hook in React is used for synchronizing side effects in function components. It allows you to run some logic when the component mounts, when some props change, or on every change. It replaced lifecycle methods like componentDidMount because it is easier to use and also brings performance benefits by running in the next frame.

useEffect improves performance by running in the next frame rather than the same frame as the render. This prevents forced layout recalculations, which can freeze the JavaScript thread, making the application more responsive.

Update batching in React is a performance optimization technique where multiple setState calls are batched together to result in a single render. This reduces the number of renders and improves performance. React 18 introduced default batching for all updates, making it more efficient than previous versions.

In React 18, all updates are batched by default. When setState is called, React schedules the update to be processed at the end of the current frame. This ensures that multiple setState calls within the same frame are batched together, resulting in fewer renders and better performance.

Suspense in React is a component used for data fetching that also introduces selective hydration. It allows parts of the application to be hydrated (made interactive) separately, reducing the time the page is frozen during hydration and improving the user experience.

Selective hydration in React works by hydrating the application suspense by suspense. Instead of freezing the entire page during hydration, React hydrates one suspense boundary at a time, making each part interactive before moving on to the next. This reduces the time the page is frozen and improves performance.

Suspense improves page performance during hydration by reducing the time the page is frozen. It allows React to hydrate parts of the application separately, making them interactive sooner and enhancing the user experience.

No, useLayoutEffect has the same behavior as componentDidMount and can reintroduce performance issues due to forced layout recalculations. React discourages the use of useLayoutEffect for this reason.

For debugging slow React applications, the recommended tools are Chrome DevTools and the React Profiler. Additionally, the 'Why Did You Render' library can be helpful in identifying unnecessary re-renders.

Some key performance features in React 19 include the stabilization of static components and improvements to server components, which are designed to enhance the performance and efficiency of React applications.

Ivan Akulov
Ivan Akulov
31 min
14 Jun, 2024

Comments

Sign in or register to post your comment.

Video Summary and Transcription

React's improvements in performance, such as the introduction of useEffect, have gone unnoticed. useEffect simplifies synchronizing logic and improves performance by eliminating forced layout calculations. Update batching optimizes rendering by combining multiple set-state calls into a single render. React 18 introduces batched set-state calls for faster performance. React Suspense and selective hydration improve user experience and debugging performance issues is best done practically. Server components, recommended debugging tools, and framework choices are also discussed.

1. React Performance and useEffect

Short description:

React's improvements in performance over the last ten years have often gone unnoticed. Today, I want to discuss the hidden changes that have made React apps faster. One such improvement is the introduction of useEffect, a hook that simplifies synchronizing logic. With useEffect, developers no longer need to use lifecycle methods like componentDidMount, which required more code. However, alongside the usability improvement came a deliberate performance enhancement, which I will explain using a quiz.

So, let's get started. Original title of this talk was last ten years of React performance, so to start, I'm pretty curious, folks, who here has already used React 19? Could you raise your hand? Oh, nice. Who here has ever used React 18? Nice. What about React 17? What about 16? What about 0.13? What about 0.3? I do not believe you. That was the first version of React. Well, maybe some people did.

Anyway, React has been around for ten years, or at least ten years it went through an awful lot of changes. Some of them improved compatibility, some of them directly aimed to improve performance. But today, I want to talk about the improvements that most developers didn't notice that I didn't notice for years, improvements that React slipped under our noses to make our apps faster. In other words, I want to talk about the invisible hand of React performance.

To start, let's talk about useEffect. Who here uses useEffect? Who here loves useEffect? One hand! Okay, yes, I'm going to show you one reason why useEffect is actually a pretty good hook. So, useEffect is a hook that lets us synchronise things, right? We can run some logic when the component mounts, or when some props change, or on every change. Before useEffect was introduced, the same thing was achievable with life-cycle methods. You would have a class component, a component written as a class, not as a function, and that class would have a render method that returns the JSX and methods like companyDidMount or companyDidUpdate which would allow me to synchronise prop changes just like useEffect but with more lines of code.

Now, when React 16.8 came out, useEffect pretty much replaced companyDidMount because it was just so much easier to use, and that was a great change, but alongside the big noticeable usability change came a much more hidden but very intentional performance change which I would like to talk with you about. And to talk about it, I have a quiz. So, I have this React component. When the component renders, it sets the document body background colour to red. When the component mounts, it sets the background colour to blue. Question, which colours will the browser render? Option A, red, then blue. Option B, blue, then red. Option C, only blue. Option D, only red. Which colours will the browser render? Who thinks it is A? Okay. Who thinks it is B? All right. Who thinks it is C? Nice. Who thinks it is D? All right. So the right answer here is C, only blue. Now, I have this code.

2. Effect of useEffect on Browser Rendering

Short description:

With useEffect, the browser renders the colors red, then blue, while with companyDidMount it only renders blue. This difference in behavior is a deliberate performance decision made during the design of useEffect, which fixed a class of performance issues. To understand this difference and the issues it addresses, we need to understand how browsers render updates and utilize caching. When reading a value that is not cached, the browser must recalculate styles and layout, resulting in a performance issue known as forced layout calculation. This issue was commonly encountered with component-mounting.

This is the same code, same component but instead of companyDidMount, it uses useEffect. Same question. Which colours will the browser render? Who thinks it is A, red, then blue? Who thinks it is B, blue, then red? Who thinks it is C, only blue? Who thinks it is D, only red? All right. Quite a few people. The right answer here is A, red, then blue. So, with useEffect, the right answer is red, then blue. With companyDidMount, the right answer is only blue. This difference is a result of a very intentional performance decision that drove useEffect design and also helped to fix a whole class of performance issues. But to understand this difference, to understand the issues it fixed, we need to take a detour into how browsers render things under the hood.

So the browser's rendering pipeline is complex. You only need to know two things about it. Thing number one, whenever a browser has to render an update, like maybe it's a timer fired, maybe I clicked something, whatever, it always goes through four stages. First, it runs the JavaScript. Then, if the JavaScript has updated the page, the browser recalculates the styles and recalculates the layout. And then, once it is done, the browser paints the results on the screen. This is the first thing we need to know, always four stages in any update. The second thing is that browsers use a lot of caching. So every time the layout updates, for example, the browser caches it and remembers it until the next time the layout has to update again. So for example, if you render the app for the first time in this update N minus one, and the browser calculates that the header has a height of 200 pixels. The browser will remember that, and keep that in memory until you say click the header, and it expands, and the header becomes 500 milliseconds, because it has changed. So when you have, for example, a button ref in React, and some JavaScript code tries to read the height of the button, the browser doesn't need to do that right on the spot. The browser will just go to the cache and read the value from there when it's been saved after the last update.

Now, imagine what happens if the button which height we are reading was just mounted? What happens if it's not yet in the cache? Take a second to think how the browser would behave then. So what would happen then is the browser will be forced to recalculate the styles and recalculate the layout ahead of time. When I'm reading something that's not in the cache, the browser is forced to recalculate the styles and layout ahead of time. So when that happens, the browser will freeze the JavaScript, compute the styles, compute the layout, and then return the height back to JavaScript. This is a performance issue that's caused a forced layout calculation. This was a pretty common problem with component-mount. Say you have a component that looks like this. Say it's a button component, it renders a button, and then it checks if the button is taller than 300 pixels, and, if yes, then it does something with the button.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

A Guide to React Rendering Behavior
React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
This transcription provides a brief guide to React rendering behavior. It explains the process of rendering, comparing new and old elements, and the importance of pure rendering without side effects. It also covers topics such as batching and double rendering, optimizing rendering and using context and Redux in React. Overall, it offers valuable insights for developers looking to understand and optimize React rendering.
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Watch video: Speeding Up Your React App With Less JavaScript
Mishko, the creator of Angular and AngularJS, discusses the challenges of website performance and JavaScript hydration. He explains the differences between client-side and server-side rendering and introduces Quik as a solution for efficient component hydration. Mishko demonstrates examples of state management and intercommunication using Quik. He highlights the performance benefits of using Quik with React and emphasizes the importance of reducing JavaScript size for better performance. Finally, he mentions the use of QUIC in both MPA and SPA applications for improved startup performance.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
Watch video: React Concurrency, Explained
React 18's concurrent rendering, specifically the useTransition hook, optimizes app performance by allowing non-urgent updates to be processed without freezing the UI. However, there are drawbacks such as longer processing time for non-urgent updates and increased CPU usage. The useTransition hook works similarly to throttling or bouncing, making it useful for addressing performance issues caused by multiple small components. Libraries like React Query may require the use of alternative APIs to handle urgent and non-urgent updates effectively.
The Future of Performance Tooling
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Today's Talk discusses the future of performance tooling, focusing on user-centric, actionable, and contextual approaches. The introduction highlights Adi Osmani's expertise in performance tools and his passion for DevTools features. The Talk explores the integration of user flows into DevTools and Lighthouse, enabling performance measurement and optimization. It also showcases the import/export feature for user flows and the collaboration potential with Lighthouse. The Talk further delves into the use of flows with other tools like web page test and Cypress, offering cross-browser testing capabilities. The actionable aspect emphasizes the importance of metrics like Interaction to Next Paint and Total Blocking Time, as well as the improvements in Lighthouse and performance debugging tools. Lastly, the Talk emphasizes the iterative nature of performance improvement and the user-centric, actionable, and contextual future of performance tooling.
Optimizing HTML5 Games: 10 Years of Learnings
JS GameDev Summit 2022JS GameDev Summit 2022
33 min
Optimizing HTML5 Games: 10 Years of Learnings
Top Content
PlayCanvas is an open-source game engine used by game developers worldwide. Optimization is crucial for HTML5 games, focusing on load times and frame rate. Texture and mesh optimization can significantly reduce download sizes. GLTF and GLB formats offer smaller file sizes and faster parsing times. Compressing game resources and using efficient file formats can improve load times. Framerate optimization and resolution scaling are important for better performance. Managing draw calls and using batching techniques can optimize performance. Browser DevTools, such as Chrome and Firefox, are useful for debugging and profiling. Detecting device performance and optimizing based on specific devices can improve game performance. Apple is making progress with WebGPU implementation. HTML5 games can be shipped to the App Store using Cordova.
Power Fixing React Performance Woes
React Advanced Conference 2023React Advanced Conference 2023
22 min
Power Fixing React Performance Woes
Top Content
Watch video: Power Fixing React Performance Woes
This Talk discusses various strategies to improve React performance, including lazy loading iframes, analyzing and optimizing bundles, fixing barrel exports and tree shaking, removing dead code, and caching expensive computations. The speaker shares their experience in identifying and addressing performance issues in a real-world application. They also highlight the importance of regularly auditing webpack and bundle analyzers, using tools like Knip to find unused code, and contributing improvements to open source libraries.

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Building WebApps That Light Up the Internet with QwikCity
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Miško Hevery
Miško Hevery
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
Next.js 13: Data Fetching Strategies
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
Alice De Mauro
Alice De Mauro
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
React Performance Debugging
React Advanced Conference 2023React Advanced Conference 2023
148 min
React Performance Debugging
Workshop
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
High-performance Next.js
React Summit 2022React Summit 2022
50 min
High-performance Next.js
Workshop
Michele Riva
Michele Riva
Next.js is a compelling framework that makes many tasks effortless by providing many out-of-the-box solutions. But as soon as our app needs to scale, it is essential to maintain high performance without compromising maintenance and server costs. In this workshop, we will see how to analyze Next.js performances, resources usage, how to scale it, and how to make the right decisions while writing the application architecture.
Maximize App Performance by Optimizing Web Fonts
Vue.js London 2023Vue.js London 2023
49 min
Maximize App Performance by Optimizing Web Fonts
WorkshopFree
Lazar Nikolov
Lazar Nikolov
You've just landed on a web page and you try to click a certain element, but just before you do, an ad loads on top of it and you end up clicking that thing instead.
That…that’s a layout shift. Everyone, developers and users alike, know that layout shifts are bad. And the later they happen, the more disruptive they are to users. In this workshop we're going to look into how web fonts cause layout shifts and explore a few strategies of loading web fonts without causing big layout shifts.
Table of Contents:What’s CLS and how it’s calculated?How fonts can cause CLS?Font loading strategies for minimizing CLSRecap and conclusion