What Refs Can Do for You

Rate this content
Bookmark

While Refs are considered an escape hatch there are times when you might just need to use them.In this talk, with the help of real world examples, we will look at what Refs can do for us in terms of code clarity and also performance gains. Think along the lines of minimising renders and avoiding flickering UIs. We will cover the restrictions for safe usage and for those of you already using these patterns make sure you are prepared for the changes coming in React 19.

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

FAQ

React 19 introduces the ability to return a cleanup function from callback refs, making them similar to useEffect and useLayoutEffect, and ensuring they are called twice in strict mode for better lifecycle management.

Refs in React provide a way to directly access and manipulate DOM elements to avoid unnecessary re-renders. They help in scenarios where only specific style properties need to be updated without re-rendering the entire component.

Callback refs in React provide more flexibility and performance benefits, as they are called synchronously when a DOM element is mounted or unmounted, allowing for immediate updates without impacting the component's lifecycle.

While CSS variables can be used for styling, JavaScript is often necessary in AG Grid to handle dynamic updates, such as moving columns, which require logic beyond static styling.

useEffect runs asynchronously after a component paints, while useLayoutEffect runs synchronously before the browser repaints. This makes useLayoutEffect suitable for scenarios where DOM updates need to happen before the browser renders.

AG Grid is designed to work with various JavaScript frameworks, including React, by offering integrations that allow developers to use framework-specific components within the grid.

AG Grid avoids using external dependencies to maintain security and ensure stability. This prevents dependency-related issues and makes it easier for users to integrate AG Grid without worrying about external library updates.

AG Grid is a data grid component that provides features like sorting, filtering, and virtualization, and it can be integrated into applications using various frameworks, including React.

AG Grid allows custom components to be used in grid columns, but if performance issues arise, such as slow rendering, techniques like using refs or memoization in React can optimize performance by reducing unnecessary re-renders.

React DevTools is a tool that can be used to monitor re-renders and identify why a component re-rendered. It can be installed as an extension in browsers like Chrome or Firefox.

Stephen Cooper
Stephen Cooper
27 min
19 Nov, 2024

Comments

Sign in or register to post your comment.
Video Summary and Transcription
Today's Talk focused on using refs and profiling Agigrid in React. The speaker shared their experience with optimizing custom cell components and performance, including using memo and leveraging the React compiler. They also discussed improving performance with manual style updates and refactoring the use of useEffect. The speaker highlighted the use of ref callbacks, which can be implemented with useLayoutEffect. React 19 introduces changes to the ref callback approach. The Talk touched on using React DevTools and CSS variables for monitoring renders. It also discussed the compatibility of Azure Grid with React and the trade-offs between using React components and vanilla JavaScript. The speaker emphasized the importance of considering the DX improvements and the complexity of not seeing a React component tree in the dev tools. The Talk concluded with a mention of AG Grid features, handling refs at various levels, and the recommendation to consult with Stephen for technical questions and application architecture.
Available in Español: What Refs Can Do for You

1. Introduction to Refs and Profiling Agigrid

Short description:

Today, I want to talk to you about what refs can do for you. I'll share some things I've learned while profiling Agigrid, focusing on different parts of React. We noticed a jumpy resizing issue with a custom component, so we investigated and recorded the profile. While there were a lot of renders, they were fast, so it's something to consider.

Today, I want to talk to you about what refs can do for you. As you've had some spoilers and here's some more information about, you know, me. So there's 10 years in the financial industry and now three years with Agigrid. And I had to add this to my slide, you know, pictures of the pets, seeing as you're all going to find out about them. So it's Toby, Rufus, and Coco. So yeah, life is busy at home. But that's my personal life.

In a professional setting, I work at Agigrid. So you've all heard the adverts today, we've got Agigrid and the AgiCharts. So you can drop these components into your application, start using them and have all these great features. But don't worry, that's not what I'm going to focus on today. I'm going to share some of the things that I've learned while profiling Agigrid. And these are things that I think as we go on this journey together, walk through the problems, we should hopefully all learn something about these different parts of React, or that's my aim at least.

So let's start here. So while we were developing Agigrid, we were running these different use cases. And one of them was, well, a user comes to us and says, I've got this custom component that I'm going to put into one of these columns. So in this case, it's like a ticker with a picture and image of the company. And they're going to resize it. And what we noticed in these testing is that, well, actually, the resizing was really jumpy. And they're like, this is a terrible user experience. So it's like, OK, what are we going to do about it? Let's investigate.

So before we jump into the complicated case of this situation, let's take a step back and see, can we actually reproduce this in a simpler case and see if there's any performance issues there? So we opened up React DevTools. I took away all the custom cell renderers. So here we're just rendering plain text cells, moved the column around, and recorded the profile. And this is what we saw. So we're not seeing any perceived performance issues in this situation. But what you can see is that we've got 254 renders for just doing a few of these resizes. But they're fast renders. So we haven't actually automatically got a problem here because we got a lot of renders. But it's something that we maybe need to consider.

Read also

2. Optimizing Custom Cell Components and Performance

Short description:

Recording the component Y is re-rendered, and parsing hook names can make debugging easier. When we simulate user-provided custom cell components with slow logic, the grid's performance is affected. The ticker cell becomes a bottleneck, causing the browser to get stuck in re-renders. By using memo and leveraging the React compiler, we can improve performance.

And while we're looking at the profile, these are two settings which I think are very, very important. So recording the component Y is actually re-rendered. So this is telling you, well, it's the cell component, and it was hook 30 that changed. And then there's another setting under the components panel where it can parse the hook names. So instead of having this undefined false, false, false, it actually gives you the names that you used in your code. So these are just a small thing which can make debugging these issues so much easier.

Like I said, we didn't really see this performance issue in the simple case. So now we put in a custom cell component, and we make it artificially slow. So we'll put some slow logic in there, maybe like a for loop, which does a lot of work, before it renders things. So these are just an idea of simulating what a user might provide to us. Because we're not in control of what the user is going to give us. But we need to make sure the grid still works well in those situations.

So when we did this, put it into the grid, we could see we had this slow behavior again. And this time in the profile, it looks quite different. We've only actually managed to render it 10 times. So this is why instead of having lots and lots and lots of different renders, and you get that smooth resizing, we've instead got this, you know, the browser gets stuck, it re-renders. The browser gets stuck, it re-renders. So you can see this with the much taller bars and the time that they were taking. And we can also quite clearly see that it's this ticker cell that we've provided, which is the bottleneck, and which is blocking the browser.

So if we quickly look at this and say, okay, well, why is this component rendering so much? Now, in our cell component, we were setting the style via the state property, say we've got left here. So our cell controller, which is what controls where all these columns are, it was saying, well, the left position is changing. And that's what you would expect. And we would simply update the state. But because we're updating the state, React is re-rendering this whole component. And because the state is being updated on that div, the custom cell is a child of that. And so if there's no memorization or any kind of catches there, that is also being re-rendered. So the first step is, well, we can wrap it and use memo, or memo. And then also this is something that the React compiler will take care of us. So I'm not going to spend much time talking about that. That helps us improve the performance.

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

React Compiler - Understanding Idiomatic React (React Forget)
React Advanced 2023React Advanced 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
Watch video: React Compiler - Understanding Idiomatic React (React Forget)
Joe Savona
Mofei Zhang
2 authors
The Talk discusses React Forget, a compiler built at Meta that aims to optimize client-side React development. It explores the use of memoization to improve performance and the vision of Forget to automatically determine dependencies at build time. Forget is named with an F-word pun and has the potential to optimize server builds and enable dead code elimination. The team plans to make Forget open-source and is focused on ensuring its quality before release.
Everything You Need to Know About React 19
React Summit US 2024React Summit US 2024
29 min
Everything You Need to Know About React 19
Watch video: Everything You Need to Know About React 19
React 19 introduces new features such as React Compiler and React Actions, which optimize code and provide better performance. The useOptimistic hook allows for optimistically updating UI, while the UseFormStatus hook tracks loading states and enables button disabling. The introduction of the 'action' attribute simplifies form handling and data retrieval. React 19 eliminates the need for useMemo and useCallback thanks to the React Compiler. The stability of React 19 has been observed in side projects without major issues.
An App Developer's Guide to React 19: What You Need to Know and Everything You Can Safely Ignore
React Summit US 2024React Summit US 2024
33 min
An App Developer's Guide to React 19: What You Need to Know and Everything You Can Safely Ignore
Watch video: An App Developer's Guide to React 19: What You Need to Know and Everything You Can Safely Ignore
Today's Talk focused on React 19 and its features, APIs, changes, and optimizations. The speaker emphasized the importance of migrating apps and building with React 19. They discussed the high-level features of React 19, including TypeScript emphasis and the testing library philosophy. The Talk also covered the APIs and integration of React 19, as well as the changes and type safety it brings. The speaker highlighted the improvements in useReducer types and the use of TypeScript. They introduced useActionState for migrating code and the useOptimistic hook for maintaining state immediacy. Real-time updates, action functions outside components, and the benefits of using the 'use' prefix in React were also discussed. The Talk touched on upgrade considerations, the role of RSEs and server actions in React, and the current state of RSC development. Overall, the Talk provided valuable insights into the new features and enhancements in React 19 and their impact on the development process.
React 19 and the Compiler for the Rest of Us
React Day Berlin 2024React Day Berlin 2024
30 min
React 19 and the Compiler for the Rest of Us
Hi everyone. I'm Johnny, an application engineer who builds user-centric React 19 applications. Today, our goal is to help you reach production mountain with React 19. Let's start by gathering a crew and discussing the motives for installing the compiler. We'll revisit React rules and explore the compiler's impact on code. The React compiler translates from JavaScript to JavaScript and provides error reporting. It enables deeper levels of optimization and focuses on user experience. To upgrade to React 19, install the latest version and be aware of any compatibility issues. Check if any custom runtime code needs to be disabled. The React compiler can be used with versions 17 or 18 if you have runtime support. The compiler removes use memos and optimizes the initialization process based on static components. It provides granular reactivity and reduces rendering, making the application feel quicker. Follow React rules and conventions to ensure compatibility. Test custom hooks, be aware of the impact on build time, and address any unexpected issues like the removal of the global JSX namespace. Debugging tools and source mapping in Chrome are useful for understanding compiler output. Enjoy translating chants and exploring the possibilities of React 19!
React Compiler - The Missing Piece for Optimizing React Applications
React Day Berlin 2024React Day Berlin 2024
30 min
React Compiler - The Missing Piece for Optimizing React Applications
Today's Talk introduces the React compiler and its optimizations in React 19. The compiler handles optimizations internally, allowing existing optimizations to coexist. React 19 also brings server components, enhanced hooks, improved reference handling, and asset loading optimization. The React compiler follows the same principles as a typical compiler, with a Babel plugin and ESLint plugin identifying optimizations. The compiler optimizes components by performing in-place updates and reducing unnecessary re-rendering. The React compiler playground helps understand the optimization process. Caching JSX and configuring the React compiler can further optimize specific components. The React compiler is compatible with React 18 and 17 with some configuration, but using React 19 is recommended. Connect with the speaker for more information and subscribe to their YouTube channel. Thank you for watching!

Workshops on related topic

Mastering React Server Components and Server Actions in React 19
React Advanced 2024React Advanced 2024
160 min
Mastering React Server Components and Server Actions in React 19
Workshop
Maurice de Beijer
Maurice de Beijer
Calling all React developers! Join us for an immersive 4-hour workshop diving deep into React Server Components and Server Actions. Discover how these game-changing technologies are revolutionizing web development and learn how to harness their full potential to build lightning-fast, efficient applications.
Explore the world of React Server Components, seamlessly blending server-side rendering with client-side interactivity for unmatched performance and user experience. Dive into React Server Actions to see how they combine client-side interactivity with server-side logic, making it easier to develop interactive applications without traditional API constraints.
Get hands-on experience with practical exercises, real-world examples, and expert guidance on implementing these technologies into your projects. Learn essential topics such as the differences between Server and Client Components, optimizing data fetching, passing data effectively, and maximizing performance with new React hooks like useActionState, useFormStatus and useOptimistic.
Whether you're new to React or a seasoned pro, this workshop will equip you with the knowledge and tools to elevate your web development skills. Stay ahead of the curve and master the cutting-edge technology of React 19. Don't miss out - sign up now and unleash the full power of React!
Evolution of Form Management in React
React Summit US 2024React Summit US 2024
72 min
Evolution of Form Management in React
Workshop
Adrian Hajdin
Adrian Hajdin
Learn how to handle forms in React using the latest features, such as startTransition, useTransition, useOptimistic, and useActionState, with and without React 19 server actions, alongside proper validation, error handling, and best practices.The workshop will begin by demonstrating traditional form handling using useState and useEffect for client-side rendering. Gradually, we'll transition to using the latest React 19 features, including server-side forms and the newest hooks for managing form states and errors. By the end of the workshop, participants will understand how to create robust forms with proper validation and error handling.Learning GoalsLatest React 19 Hooks — useTransition, useFormStatus, useOptimistic, useActionState, useDeferredValueServer ActionsRevalidationsServer-side ValidationError handlingSecurity practices