Rendering: To Sync or Not to Sync?

Rate this content
Bookmark

Let’s dive deep into React rendering and evaluate the implication of Concurrent Rendering and automated batching on code that previously relied on the synchronous nature of v17. Does it always make things better? With a real world case study, we evaluate useSyncExternalStore and flushSync as tools to restore synchronous rendering to avoid “visual tearing”. Working through the trade-offs of these approaches will give us new insights into React rendering and hints on how we can optimise our applications.

Stephen Cooper
Stephen Cooper
28 min
13 Nov, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This Talk discusses rendering and synchronization in React 18. It addresses issues such as flashing rows and wiping out when scrolling. The use of usync-externalstore for concurrent reads and the potential misuse of APIs are explored. Debugging techniques using React Profiler and flush-sync are discussed. The talk also covers performance considerations for different machines and the importance of testing and considering alternative solutions.

1. Introduction to Rendering and Sync

Short description:

Today I want to talk to you about rendering and whether we're going to sync or not sync. We're going to have to try and work out what is going on. The first bug we're gonna look at is clicking the scroll bar causes this flash. The second issue we've got is when you're scrolling, they're completely wiping out. We've upgraded to version 18 and switch to CreateRoot, enabling concurrent rendering features and automatic batching. Let's look at the code which is causing the updates for the road, and there's nothing exciting here. But I think there's some prime suspects for this issue in version 18, concurrent rendering and automated batching.

♪♪ Today I want to talk to you about rendering and whether we're going to sync or not sync. There was a funny typo when this first got shared on Twitter, where it was actually S-I-N-K, and I was thinking, oh no, is that what they're predicting my talk to be? But let's hope not. So, to sync or not to sync? Let's dive into this. It should be hopefully be an easy question to answer.

Which of these grids is better? So, on the left, we've got Agigrid running in version 17 of React, where you've got this nice, smooth scrolling, you can click the scroll bar, and the rows just appear in the right place. But then you upgrade to version 18. So, this isn't a live version of Agigrid, this is an older version which had this issue. You click the scroll bar and the rows flash, or you start scrolling up and down and the rows blank out. And it's like, as you can tell, this is not what we want the user experience to be. So, we're going to have to try and work out what is going on.

So, as you know, I'm Steve, and I do work at Agigrid, I'm on the core grid team. And so, Agigrid is what we're trying to do is create the best JavaScript data table, whether that's in React or any of the other frameworks. It's a free tier as well as the Enterprise, and if you want to find out more, do come speak to us at the booth. We'd love to talk to you about all of it. But enough about that, let's try and clarify what we're trying to fix and how React has changed, how we can try and work out what those changes are, and then how we can fix it.

The first bug we're gonna look at is clicking the scroll bar causes this flash. Let's see, can you see that? Yes. And then, the second issue we've got is when you're scrolling, they're completely wiping out. Okay, and so, this is the only line of code which is different between those two examples. So, we've upgraded to version 18, and then we switch to CreateRoot. So, when you're using render, it's the equivalent, basically, of the rendering from version 17, but now with version 18, switch to CreateRoot, and then you're gonna start enabling all these concurrent rendering features and automatic batching. And so, that's what we're gonna do. We're gonna go bug hunting.

The first thing to do is, well, let's look at the code which is causing the updates for the road, and there's nothing exciting here. It's just state. So, when the road's changing, you scroll and you need to look at new roads. We're gonna update which roads are displayed. So, there's nothing really, I mean, unusual there, or complicated, or anything that should be going wrong. But I think there's some prime suspects for this issue in version 18, concurrent rendering and also automated batching. And what we're gonna do is, and see if it's these two features which are now interacting negatively with Aggrid's row virtualization.

2. Row Virtualization and Rendering Changes

Short description:

Row virtualization is a critical performance feature for data grids. Rendering only the visible rows in the viewport prevents overloading the browser. In version 18, there is a flash issue due to changes in rendering, which now has priority-based instructions. These changes, while enabling features like useTransition, can have side effects. Check the React GitHub discussion groups for more details and context. Ivan's talk is also recommended for further understanding.

So, I guess, first of all, what is row virtualization? This is a critical performance feature for any data grid. If you want to show thousands and thousands of rows, you don't want to have to render all of that out in HTML, because you're gonna crash your browser and the experience is gonna be really, I guess, slow and difficult. But the main thing is, you don't want to overload the browser because drawing HTML is quite expensive.

So, what we're gonna do is we only render the rows that are actually visible in the viewport. So, here we go. So, a way to imagine the scrolling is we scroll, the viewport changes, and then at this point, if the browser gets to repaint, it's gonna repaint an empty grid, because the rows haven't been updated yet. And then the rows get updated after we've based on the new position of the viewport. So, I think what we can kind of imagine that's happening is that the rows aren't being updated quick enough, as well as the viewport. And so, another way we can look at this is in the DevTools profile.

So, in version 17, we'll take this benchmark of this action where we scroll and update the viewport. And the main thing to take away from this chart is that there's a single function call, and then the browser paints. So, what that represents is it's scrolling, changing where the viewport is, and rendering the rows all synchronously, and then the browser is painting. So, you don't get any kind of flash. And if we do the same thing now with version 18, it should be quite apparent where this flash is coming from, or the result of that break. So, the scroll happens, then the browser is actually getting a chance to repaint, which is why we're now getting this empty set of rows before the rows are then rendered. So, we're getting two paints instead of one. There we go. And so, this is something that we need to be aware of in version 18. So, rendering is no longer a just purely sequential set of instructions. But there's priority-based in it. And a lot of the new features in React, they require the rendering to be interruptible and support yielding to the browser. So, useTransition is a great example of this. So, it's letting you update state without blocking the UI. But these changes in the rendering have some side effects and we've run into them here in this situation. So, I'm not gonna go deeper into all of the concurrent rendering and all of that stuff. There's a lot of good information you can get on the, both on the React, GitHub discussion groups. There's so many good nuggets of information in there in the comments and in the responses. So, if you haven't looked at these discussions before, that's definitely somewhere I would say, take a look if you want to get some more low-level details or just context behind some of these changes. Another great tool is from Ivan and he's got another talk later on today. So, I'd recommend listening to him because this one definitely helps explain a lot of these concepts.

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
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into 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
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
The Future of Performance Tooling
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
Understanding React’s Fiber Architecture
React Advanced Conference 2022React Advanced Conference 2022
29 min
Understanding React’s Fiber Architecture
Top Content
We've heard a lot about React's Fiber Architecture, but it feels like few of us understand it in depth (or have the time to). In this talk, Tejas will go over his best attempt at understanding Fiber (reviewed by other experts), and present it in an 'explain-like-I'm-five years old' way.
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
The open source PlayCanvas game engine is built specifically for the browser, incorporating 10 years of learnings about optimization. In this talk, you will discover the secret sauce that enables PlayCanvas to generate games with lightning fast load times and rock solid frame rates.

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 🤐)
Concurrent Rendering Adventures in React 18
React Advanced Conference 2021React Advanced Conference 2021
132 min
Concurrent Rendering Adventures in React 18
Top Content
Featured WorkshopFree
Maurice de Beijer
Maurice de Beijer
With the release of React 18 we finally get the long awaited concurrent rendering. But how is that going to affect your application? What are the benefits of concurrent rendering in React? What do you need to do to switch to concurrent rendering when you upgrade to React 18? And what if you don’t want or can’t use concurrent rendering yet?

There are some behavior changes you need to be aware of! In this workshop we will cover all of those subjects and more.

Join me with your laptop in this interactive workshop. You will see how easy it is to switch to concurrent rendering in your React application. You will learn all about concurrent rendering, SuspenseList, the startTransition API and more.
Getting Started with Suspense and Concurrent Rendering in React
React Summit 2020React Summit 2020
125 min
Getting Started with Suspense and Concurrent Rendering in React
Featured Workshop
Maurice de Beijer
Maurice de Beijer
React keeps on evolving and making hard things easier for the average developer.
One case, where React was not particularly hard but very repetitive, is working with AJAX request. There is always the trinity of loading, success and possible error states that had to be handled each time. But no more as the `<Suspense />` component makes life much easier.
Another case is performance of larger and complex applications. Usually React is fast enough but with a large application rendering components can conflict with user interactions. Concurrent rendering will, mostly automatically, take care of this.
You will learn all about using <Suspense />, showing loading indicators and handling errors. You will see how easy it is to get started with concurrent rendering. You will make suspense even more capable combining it with concurrent rendering, the `useTransition()` hook and the <SuspenseList /> component.
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 🤐)