React is a fantastic tool to implement complicated applications fast, we all know it. But are they going to be fast when implemented fast? Let’s talk about re-renders and their danger in react: how easy it is to make a mistake, why some small mistakes can have a huge downstream effect, and how to avoid and prevent them.
This is a deep-dive type of talk, that focuses on why React components re-render, what kind of performance impact it can have, and what to do about it
Hi everyone, my name is Nadia. So first, a little bit of introduction. I am a Frontend architect, I am a coder, I am a writer. I used to work in Atlassian for a few years, worked on general frontend and now I am a founding engineer in the small startup that is called Pyn in Australia. So the topic of React performance and especially how re-renders affects React performance is something like a passion of mine. I find it fascinating that just one tiny change in the right place can either completely destroy or vastly improve performance of a huge application. So the knowledge about this topic is what I want to share with you today.
What exactly is re-render?
[01:06] But first, what exactly is re-render and why do we want to talk about re-renders in the context of performance.
So generally speaking, we have two major stages of React life cycle that we need to care about. First one is initial render. When an app is first mounted and appears on the screen and then a re-render. A re-render is second and all the consecutive renders of an app that is already on the screen.
[01:41] And from code perspective, we have at least three ways to trigger re-render of a component. First is the most known one. It's when state or props change, this is when a component will be re-rendered. Second one, if we use a context, then when a value changes, every component that uses this value will also re-render. And the third and most underappreciated one is when a parent component re-renders or if we look from the top, that means that when the component re-renders itself, it will re-render every single child that it has.
If we want to visualize the last one because it's the most important one, it'll look something like this. We have a tree of components, the top one will re-render and this re-render will trigger a re-render of all the children there and then all the children beneath. So it'll be a whole chain of re-render triggers from them from the top.
[02:44] And generally speaking, re-render itself is not something that we would want to fight with because it's an essential part of React life cycle. It's when React updates all the data that has changed. What we want to avoid at all cost is unnecessary re-renders. And by unnecessary re-renders, I mean something like this.
So imagine we have an input component somewhere at the bottom. We type something there and then this component naturally will re-render itself. That is good and that is expected. What we don't want is when we type in this tiny input component, to re-render the entire app. This, depending on the size of the app, can be extremely slow. And in today's world, users will expect all the interactions on the page to be really, really fast. So unnecessary re-renders is a performance killer.
[03:40] And to demonstrate to you how bad those can be, I even implemented a little bit of an app. An app just renders a list of components and has a little bit of interactivity so take a look. On the right performance app, I click everywhere and everything is instantaneous. On the left, exactly the same app but I made a couple mistakes there and look how unbearably slow all of this is. Just a few tiny mistakes in the right places and I just destroyed this app, and it's just a list of components.
[04:14] So common mistakes that lead to performance like that and also useful performance tips and tricks to avoid re-renders of the entire app is what I want to share with you today. Let's start with mistakes.
Mistake #1. The myth of useMemo and useCallback
The very first one is one of my favorites, and is what I call the myth of useMemo and useCallback. So as probably most of you know, React uses referential equality when it compares props or dependencies in all various hooks. And referential equality is basically this. We have two arrays or two objects if we want to compare them. If we do it like this, the result will be false because we are comparing them by the reference, not by the actual value. And from re-renders perspective, it's something like this, we have a component, it renders a child component, I pass a value to this child component that is in array. If I do it like this, during a re-render, this value will become a completely different value. So if React compares those props, React will think that value prop has changed.
[05:28] UseMemo and useCallback hooks. Hooks that allow you to memorize those value basically to preserve reference to this value between re-renders. So if I extract use this array into useMemo hook, then when re-render happens, React will think that value in a child component will be exactly the same.
And the fact that one of the most important reasons why a component to render is a state or prop change, in combination with how those hooks work led to the wild widespread belief that if we memorize all the props on a component that will prevent this component from a re-rendering.
[06:14] And this results in something that I call a useMemo or useCallback hell, because memorizing absolutely everything leads to your app having useMemo, useCallback and then another useCallback and it's just useMemo and useCallback everywhere and the app becomes incomprehensible and completely not readable and not debuggable. So I think those become really horrible. But the worst part of all of this is that it's actually useless, because a way for getting one key component in all of this construction.
So if we take a look for example at this code we see a component, it has a child component and then onClick prop. And we want to prevent child components from re-rendering by wrapping onClick in useCallback hook. But what exactly can trigger child component to re-render? We prevented prop from changes, the only thing that is left when a parent component re-renders. So we will trigger a state for example, child component will re-render and React will not actually check whether prop has changed or not at the stage, because React's natural way of dealing with components is, component re-renders and then re-render every single child. Wrapping onClick here in useCallback is just completely useless, we are doing nothing here.
[07:47] The only way to prevent child components from re-rendering when the parent component re-renders is actually wrap it in React.memo utility. And in this scenario when a parent component re-renders, the re-render of this child will be stopped or in this case component React will stop and then will start comparing all the props with the previous value, and if all of they are the same, then nothing will be re-rendered.
So from code perspective, when we have just a child component and then a useCallback that wraps a prop, it's useless. It does nothing. It just consumes a little bit of computational power. It should be something like this or just remember useCallback. Child component wrapped in React.memo and then and only then useCallback will be actually useful.
Mistake #2. Creating components in render function
[08:47] Second mistake and this one is the major performance killer in React applications. Creating components in render functions. Again I remember the app and the app is just a list, it accepts countries as a prop and then we iterate all those countries and re-render something. In real life, obviously we would want this button to have some styles, to have some functionality, so in real life I would want to extract this button and make it a component.
And what people often do is they extract it as a component and create it inside a parent component. Usually the reason for this is, it's just much easier to pass additional data to it that is derived from state but when we do something like this during every single re-render of the big list component, React will recreate the item component completely from scratch. React will just unmount everything that is already rendered and then remount all those list components. And this is not only going to be really slow, mounting is twice as slow as just re-render. It is also going to be visible on the screen because what will happen is a list component with items, list re-renders, React will think that all the items created inside list is a new component now. So it will destroy all those items, remove them from the screen and then recreate them back. So sometimes we'll see visible flash on the screen and also numerous bugs with focus. So the way to fix this of course is just never do something like this and just create components outside of big components. Never create components in line.
Mistake #3. Context provider
[10:51] Third mistake that is probably the most important source for all those spontaneous and unnoticeable re-renders across the entire app is context provider. So context is a really useful tool when we need to pass some data and avoid props drilling. So with context we can do this. We can just escape all the components in between and pass data from the top component to the bottom component. Without context, what we would have to do is pass data through every single component between the top one and the bottom one, which will cause all the middle components to just explode with props and unnecessary data and just turn into a nightmare of refactoring in six months.
But there is one caveat with context. When a context value changes, React would also need to update everything that is using this context value. And that means that React needs to re-render every single component that uses context value.
[11:59] And from coding perspective that looks something like this. We have a component, we have context provider and we need to pass value there. So what will happen if this component re-renders by some reason? Remember differential equality, we have an object that will pass to context provider, component re-renders, React thinks that the object is a different object, it thinks that a value changes and then it'll just unnecessarily re-render every single component that uses this context. And the way to fix it would be just to use a useMemo on this value always. I would say this is one of the very cases of premature optimization that you actually want because debugging re-renders that are happening because of the changes in context, just a nightmare to do them.
[12:56] Okay, so let's now stop depressing ourselves over the mistakes and talk a little bit about the actual tricks.
Trick #1. Moving state down
One of the most important one in your arsenal against unnecessary re-renders is the pattern that is called "Moving state down." So if we look at the code, we have a component, it renders a lot of stuff, it's very heavy and at some point we implemented a button there, click on the button, opens the model dialogue. Super simple functionality, this whole implementation.
[13:31] So what will happen in this big component from re-renders perspective? We click on a button, we update state and then this entire thing re-renders because when state is updated, every single child in the component will re-render. And of course something like this is going to be really, really slow. If it's a really big app, click on a button and then opening a model dialogue could cause a visible delay because React needs to re-render everything first before actually opening the dialogue. Our users will be very disappointed. The way to fix it is what is called "moving state down." This state is actually quite separated from the actual functionality of this big app. So what we can do is just to extract all of this and wrap it in component itself, and then use it back in this big component.
So now from re-renders perspective what will happen? We click on the button, state is updated, children are re-rendered. But in this case children are just a button and model dialogue. The big component will just sit there and do nothing. That is exactly what we want, opening of the dialogue will now be as fast as possible.
Trick #2. Wrapping state around children
[14:53] Second pattern, and this one probably is the most underappreciated pattern from the series and also the least known one. That's "wrapping state around children." It's a little bit similar to "moving state down." So again, we have a component. In this case we want to, for example, listen for a scroll event. So what we will do here from re-renders perspective, again.
User scrolls, we are triggering state update, update is triggered, that triggers re-render of the entire big component and again everything re-renders. But in this case we cannot just move in the state outside because this div is actually wrapping the entire component. But what we can do is we can still extract it outside, create a new component out of all of this and then pass everything that was between those divs as children.
[15:57] What will happen here from re-renders perspective and how to use it. So now we scroll, we trigger state update, update is triggered, it triggers re-renders, the scroll component re-renders itself, but everything that is inside here belongs to the parent. The child component doesn't know about all of this. From the scroll component perspective, all of this is just a prop. So all of this will not re-render. Now this app becomes as fast as possible again without any memorization, without anything.
Trick #3. Memorizing part of the render tree
[16:38] And last but not least, "memorizing part of render tree." So when you have a big component, you use some state here and there, but you cannot neither move a state down or just wrap it around children because it's just scattered across the app. But also if you want to improve performance of this app a little bit and you have a big chunk of this stream that is not dependent on the state, what you can do is just memorize this entire stream. In this case again, React update is triggered, re-render is triggered, no dependency in this memo. So useMemo will just return exactly the same value that was before. It will not update anything and performance of this big app is going to be much better than without that.
Oh that was a lot of information. I hope you found some of it at least useful. A little bit of a recap for everyone. If you are not using useMemo and useCallback the correct way, which is the wrapping component in React.memo and memorizing every single one of them, they become useless, you can just remove them.
Creating components inside render function is the biggest performance killer ever. Never do it. It should be your mantra.
Always memorize values in the context provider. That will prevent React context consumers from re-rendering unnecessarily.
Move state down and wrapping state around children are the most important tools in your fight against unnecessary re-renders. And if both of those are not possible for some reason you can also memorize expensive parts of render tree.
If you want to read a little bit more about all of this or play around with the bad app and the good app, here are the links, feel free to do it. I write a lot about all of those stuff and all different various patterns in my blog. And feel free to connect with me on Twitter or LinkedIn. Always happy to chat and answer questions. Thank you.
[19:09] Nathaniel Okenwa: Thank you so much Nadia. That was a really amazing talk. I had to take a picture of that slide at the end because there's some of those takeaways that I want to make sure I am using myself. Let's jump into some questions. I am going to ask that if you are in the audience and maybe you are quickly going off to another talk, that's totally fine. Let's just keep the noise down so that we can hear all these questions even in the back. All right, let's just jump straight into it. What will happen if we pass the object to a child component which is exported with React.memo? Not sure if I've read that correctly and you need to read it.
[19:42] Nadia Makarevich: So if a child component is wrapped in React.memo and we're just rendering it, then we need to memorize this object. Otherwise, if the object is not memorized, the component that is wrapped in React.memo will still re-render because React thinks that props are different so it will trigger a re-render.
[20:03] Nathaniel Okenwa: That makes sense. And one thing, this is also something that popped into my head. Why is React.memo with the child not just the default behavior for rendering children? Because it makes so much sense to use it that way.
[20:16] Nadia Makarevich: It makes so much sense. And as far as I know the React team, I'm not part of it. So I just use the internet. They're experimenting with doing exactly that during build, but just memorizing everything also has its costs. So if you just memorize everything, it might make your app slightly slower. Because again, if everything is wrapped in React.memo, but you're not wrapping everything in the useMemo and useCallback, those are useless, but you're still doing stuff during that. So it can increase your initial render.
Nathaniel Okenwa: That makes sense.
Nadia Makarevich: It may or may not save you from re-renders, but will definitely increase your initial render.
[20:53] Nathaniel Okenwa: That makes sense as well. And another one we've got. Is it okay to render a component even if it's not visible/open by default?
Nadia Makarevich: Well, it depends.
Nathaniel Okenwa: Yeah, in my head. I was also thinking sometimes we may and sometimes we may not, but do you have any thoughts or perspective on the answer?
[21:09] Nadia Makarevich: For example, for model dialogues, if you want to make it like some smooth transition that slowly appears, you would have to render it in advance a little bit. So it's there but invisible and then it appears. So this is the case where you would want to render it, but it's still invisible.
[21:27] Nathaniel Okenwa: That makes sense. That makes sense. I think that's all of the questions that we have. Are there any more? Maybe there are some that I missed. Make sure you keep your questions coming. You can join at the Slido at 1721 and if you have more questions as well, maybe you want to jump in depth, you can find Nadia over at the speakers discussion room just right around the corner. All right folks, thank you so much Nadia. Let's give her one more round of applause.
Nadia Makarevich: Thank you.