- Podcasts
- The React Show
- How does React Render?
How does React Render?
The React Show
- October 1, 2021
- 1 h 26 min
- Season 1, episode 18
About this episodeHow does React actually render your components? When is it going to invoke your component’s render code and when is it not? How…
How does React actually render your components? When is it going to invoke your component’s render code and when is it not? How intelligent is the fabled React tree diffing algorithm? We’re going to take an in-depth look at how React renders and talk about the internal algorithms and how that can and should influence the way you write React code.
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
How does React Render?
Welcome to the React Show. It's gonna be a lot of fun, like I always say it is. Um yeah, we're gonna look at trees today. Oh yeah, so, anyways, um, we're gonna look at how does React actually render uh a tree of components? Um, how does rendering work? Like if you've ever wondered um when React is gonna render things, what order it does it in, that kind of thing, um we're gonna talk about the internals of React's algorithm today and um really get in-depth in looking at how that works. And I think that will help um a lot if you're writing your own components and you want to know the best way to do it in terms of uh performance and if you're just curious. Um so yeah, we're gonna we're gonna take a deep dive on that. Um it's if you're not familiar with it yet, this is actually uh largely based on uh a book that I wrote, um Foundations of High Performance React. So, you know, if you find this subject interesting, you can um get even more into the weeds, uh so to speak, with with that book. Um yeah, so I'm I'm really excited to talk about this. I find it a really fascinating topic. Um and yeah, so welcome to the show. Um we're with Al Creek, uh high performance React Consultancy. Uh I'm Thomas uh with my co-host Austin. Uh welcome to the show, Austin. Howdy do. As always, great to have you. Um and yeah, so if you have any feedback or questions, uh feel free to email us at thereact show at alcreek.studio. And if you haven't already, um don't forget to subscribe, rate, and comment this podcast in your favorite podcasting platform. Um it definitely does help us continue to bring shows like this to you every week. And yeah, that's what we got for the intro. So uh I think uh I'll just give you a quick overview of of what we're planning to talk about today. Um, and and that is the the full process of rendering and and reconciliation. So not necessarily um some of the details that are you know not as relevant to like uh create element and and stuff that happens before, but we'll try to go over like you know how React actually walks through a tree and and connects that to the DOM, that kind of thing. Um so yeah, uh once again, uh thank you for joining us. Um and yeah, uh we'll we'll get into it. Is there uh anything you you had to say, Austin?
No, uh I love the this topic that we're going to be working on because it's really important to know what the tool you're working with and how it works internally so that you can make sure it helps you with debugging your application where you're like, oh, okay, it could be rendering this way. Because you you know uh at a deeper level how things are working and yeah, like you said, it it helps when you're creating your own custom elements, uh, how to do it properly.
Yeah, absolutely. Um so yeah, we'll get into it. Um to start with, um, I'll just give you a quick overview of the process that's involved. Um so the first thing is even before you run your program, uh there's a compilation step usually where we compile JSX to um create element function calls. This is actually this detail has changed slightly since um earlier versions of React, but the essence is the same. Basically, your JSX code needs to get compiled into regular JavaScript code because JSX is not itself JavaScript. Um and so that step happens, and as a part of that step, um you can think of it as basically a tree of objects gets created. And for every uh uh element that would eventually get um rendered to the DOM, we record the type. So like that would be like div or span or a text node or something like that. And then we record the props. And so that would be you know class name or or any other um props that you might normally attach to an HTML element or that you might pass through a React um tree. So props that custom props that you make and pass to other components. And that actually also includes um the children. So it's attached as uh essentially a prop. Um and that would be an array of objects of the same thing, so of type and props. Um so that's the the first thing is, and I I don't want to talk too much about um this in this episode. Um we're focusing on other things, but it's important to understand that this step is what starts to create our tree and it has the type and the props. Um the next thing is uh render. So, how do we take all of these elements that we compiled in the previous step and actually put them on the screen and set up the events and do that kind of thing? Um that that's our our render step. Um and as a part of that, um after things get rendered, that's when effects and component did mount gets run, things like that. And then we also have reconciliation, which is a part of the render phase after our first initial render. And so reconciliation figures out, and this is like sort of what people know as the you know the secret sauce of React or whatever, what makes React special is the ability for React to figure out which DOM nodes to actually update. Um and and that's like um kind of the key innovation to a large degree of React itself. Um so we'll look at that um algorithm and and how that works. Um and yeah, so that's a a quick overview. Um did you did you have any thoughts on any of that, Austin?
All right, awesome. Yeah, so first um before we can get I I want to talk about reconciliation too. I'll admit like that's really fun and interesting. Um but before we get to that, we have to understand the actual render phase itself, otherwise the reconciliation details won't make as much sense. So we're gonna start with render. So you can think of render as just like a function called render. And it takes um, at least to start with in our uh walkthrough here, just one or I guess two arguments. So one argument would be a tree of elements that were created in the the compilation step. Um it's actually a little more complicated than that, but we can just think of it as like it takes a tree of elements, you know, that have a type div, you know, and class name, say foo, children is an array, and maybe it has you know uh object in there which is a span. Um so you can see how if you were given that you know um object which represents a tree of components to render, you can see how that um can be mapped to actual DOM nodes. Um I think does that make sense, Austin? Like that would make a pretty clear mapping um to the DOM nodes that end up on the screen?
So pretty much like your your entry point uh when you pass in your app to the React DOM, that is like the trunk of the tree, and then all of the child components are theoretically like branches off of like that, grow out of that and split into their own children, and they can have children as well, right?
Yeah, exactly. Yep. So we we start with this tree of elements, that's one of the arguments to our render function. And then the other one would be the like root DOM node that you pass in when you start your React render. I I forget the name of it, like um React DOM dot render, whatever. Um so that's like the actual container div or whatever. Um so that's all you need, actually, is those two things. And then the render function, what it does is it looks at these objects in this tree. So like it takes the first object and it says, okay, type div. So it creates a DOM element in JavaScript with type div, and then it just iterates over each of the properties and sets those properties on that DOM element, whether it's class name or style or whatever they might be. Um it just walks through all those properties except for the children element, which it handles later. Um, or children property. So it sets all those properties on this newly created DOM element. Um then it calls this render function recursively on each of the children of that initial element. So it takes the children prop, which is an array, and walks through each of those children, just passing in the you know child element to the render function. And as the like root DOM node, it passes in the new DOM element that we created. And so if you do this in a recursive nature, you will walk the whole tree, creating a new tree of actual DOM elements with all of its properties set. Um are you following still, Austin? Yeah, that makes sense to me. Okay, cool. So so now we have like essentially this tree of DOM elements. Um and the way that I I think it um works, you know, technically, like internally, is um anytime a part of the tree gets finished, like React finishes calling render on all the children, and there's no more children to call render on. Um so at the bottom of our render function, basically, we just append the newly created DOM element for that render call to whatever was passed in as the parent DOM element or the root DOM element. And so we just walk our way back up the tree until we get to the very top and we attach our tree to the container DOM element that was passed in at the very beginning. So now we've taken our React components and created them to actual DOM elements that work and function in your browser. Um that sound pretty awesome or what, Austin?
Yeah, so so now you're like, okay, great. Um we just ex and and so maybe uh I think even before I move on, this is sort of an aside, but I think it's pretty neat. Um when when I was saying here, like um you know, rendering our components, you know, like if you have uh function-based components, you can think of that as literally just invoking the function and taking its return value. And the return value is that tree of elements that represents that component. It's that simple. It's just invoke the function and use the return value in this render process. I I don't know. I think that's pretty neat, but um yeah, so uh we'll keep going here. So, like Austin said, what happens next? So we got our DOM elements and they're on the browser screen and you can interact with them, and it's it's a regular web page now, right? Um but now let's say you want to have an interactive web application. Like that's why we're using React, right? You know? Um so how would you um go about handling that? Like let's say um you you have a state change, like you want you have a like a toggle button. It you know, you click it, it shows something, you click it again, it hides something, or or whatever it might be. How are you how how is that gonna fit in? Um so we can take like uh a very naive approach and say anytime there's a state change, so I click the button and I need to update what's on the screen. What we could do is re-render the entire tree again, right? Just walk, like call all of our function components, get the return values, build up a tree of elements, walk through that tree, and just replace what was on the screen with a new tree of DOM elements. So that's like a super simple way that you you could do this, right? Um does does that make sense, Austin? Like just sort of calling render and redoing all that work.
Yeah. Well, there is so there's first of all, there's one issue with that approach, and that is what do you do with um state in the browser? So the browser itself maintains tons and tons of state. I don't know if people often think about this, but like let's say the user clicks um a select drop down, and they're hovering over they scroll down a bit and they're hovering over something. Or maybe they scrolled the page down. Um how how is that state gonna be maintained if we're just wiping out the existing tree and replacing it with a new DOM tree? Or what about like event handlers and things like that? Um so that would be you you can't you can't create a very good interactive web application if that was the approach you took, because you you would probably find it's a really horrible user experience because you either lose all the state that the browser is maintaining, or you have to like maintain all that state yourself somehow. So while that would be like a quick and dirty approach, it it's probably too dirty to be that useful.
But it's pretty amazing to think uh how like the the simplicity of the thing you just mentioned, like just opening a select, or even just like where your like your mouse is on the screen, right? Uh like the the browser is tracking the coordinates of your mouse. When you click on an element, it knows like that, like it opens that one up and it maintains like the position of the element now, uh uh the position of your mouse now contextualized to that element, and it's aware of like where where you are, and it's picking up like okay, we're hovering over the first option, and it knows and it can handle that state of hovering over that first option. Uh this is like the state that we aren't even aware of uh managing.
Yeah, yeah, absolutely. It's um it's actually an interesting thing though, because if you think about it, um what often what I often see with um React applications is they end up re-implementing a lot of these things in React. And a lot of times people think that's because they want it to like have maybe the same look and feel or something. But really to what I think it is, is a lot of times the React programmer wants to be able to manage and store and retain that state so that when their thing gets re-rendered, they don't lose it. Um and and so we end up recreating all this stuff in React, even though it exists in the browser.
Well, that that's a that's kind of like where my question lies is uh how like I'm assuming that the React library itself uh it integrates with the browser's natural functions to uh to manage these. Where where does that occur in relation to like the tree rendering? Is this like a separate uh process that's running in the background with React? That's like uh it's just a bunch of event listeners, I guess.
So the truth is it doesn't integrate. Um remember the part where I was like uh in the render function where we set properties? Um that's it. So like if you have an event handler, it sets the event handler. And it does a little bit more to like make sure that when something gets unmounted, it unsets the event handler. But as far as I know, it it doesn't have any significant amount of itself dedicated towards trying to manage that. And I think that's why we end up with these React components that duplicate things that exist in the browser. It's because people might not understand this whole process that we're talking about. And so they're um, you know, select, you know, something they're rendering a select box and they're seeing that it's getting like re um drawn on the screen and losing their state. Or a case that like we're both familiar with um uh one of our clients is uh they have um like a table component and with like uh infinite scroll and stuff. And if you're navigating between pages, it doesn't maintain that scrolled state at all. Whereas like if you had written this um with like plain HTML pages or whatever, that would just happen. Um so it's really, in my opinion, React doesn't really do anything. It's sort of on you to make sure that you're not um re like unmounting and remounting that original DOM element. And that's the only way you can really have it work. So like if you want the browser to maintain the state that it normally maintains, you gotta make sure that component never gets unmounted by React. Does that make sense?
Yeah, that's really cool. Um what are uh it sounds like there's quite a bit of performance implications in that as well. So like you have one page that you have this component that you don't want to unmount, even though you leave the page to some degree. Um what what are the like cleanup implications of that when you're like okay, you've already you're out of this context of that table that you want to remember the scroll position on, and now you're in a different part of the app. Uh what are like what are the proper ways of making sure that okay, we don't need to have that one mounted anymore.
Right. And then my question was then following up was like, okay, say you've kept this table mounted in the background so that when you come back to it you remember, but then your the user is like in a totally different context of your app. The the table memory doesn't even matter anymore. It sounds like there could be a lot of implications to like accidentally having a ton of these kind of remembered in the background and start to bog down your your application.
Yeah. Um I actually I think that's a really fantastic question, and I don't actually know of a good answer in the React community for that right now. Like I think the approach most people take is they don't try to keep things mounted, they just let it you know get unmounted and they try to store whatever state they want to restore later somewhere in their app. So like for scroll position, they might capture the last scroll position before the user navigates to a new page, and then if they go back to that page, they try to restore that scroll position. Um I think it's very unfortunate that that's the way it that's what we're doing. But to be honest, there's not a lot of great solutions because, like you said, if you just try To keep everything in memory, that's a complicated, essentially caching system. And caching systems are always tricky and always hard to get right. And if you're not being super careful about that in your regular application program where you're just trying to get features out, you're gonna have a ton of problems. So, you know, browsers have you know decades of work put into them to make that uh work well and not be in you know it'd be as optimized as it really can be. Um and if you're trying to duplicate that in your like just React application you're building for some other purpose, chances are you're not gonna do it very well.
Yeah, I'm like trying to think of all sorts of ways that you could store it, and it it sounds quite complicated just uh just for this one instance of like remembering that table instance has this scroll position, and you like store that maybe within local storage or within your app, like some sort of persisted state, and then you have all these uh name tables with their name positions, and it's like when do those when does that cache invalidate? Yeah, it's it's so funny how such a trivial thing that no one would even think about when they're using an application is like utterly critical to having a high performance React application.
Yeah, absolutely. I think it's something that people just seem to uh approach as like I'm running into it not doing what I want, so I'm gonna add more state, you know, use state or whatever, or just try to work around it, and it's usually not very good, and it's usually kind of hacky, but that's how it goes. And I think it I think it really does point out the I think a sort of deficiency of React and things like it, which is they're sort of forcing you to throw out a long history and a lot of effort that's been put into browsers to handle a lot of these these things for us. Um there's there are potentially ways around it, maybe, um, but it's like I said from the very beginning, I don't think there's a good answer here.
Yeah, well, I think it it ties into the the big next subject, which is reconciliation, which is the the fancy name for how does React figure out um what to update in the DOM? Uh so if we remember back to our render function, we had a a tree of elements that we are converting to DOM elements and setting their properties and you know, eventually attaching this to the browser's DOM. Now we've got this tree in the DOM. What do we do next? Well, the first thing is we need to modify our our previous render function to also store the tree output from render um from our last render. So basically when we uh take that initial like tree of elements where it has the type and the props, we need to also add another um key to that, which is like DOM node or something. And so instead of throwing away our input tree of elements, we can modify it or or do it in a functional way to also attach the DOM element on the screen, like a pointer to it. So like um if we have a div at the very beginning at the top of our tree, it'll have another key in it called DOM node. And at the end of our render function, that will point to the div DOM node that is actually in the browser at that moment. So basically, we need to store the the current state um and and how our tree maps to what's in the browser. Does that make sense?
Yeah, I don't know if this is actually I don't actually don't know if this is how it's done, but I was just thinking like your use state, that state could also be stored in these elements, that tree of elements. So each element would have you know like a state key that maps to the state for that element. I don't know if that's actually how it works, but you could do that um and and get like that's a way of thinking about it for sure. And you could also do that with like your other hooks, like effects and stuff. They could all be attached to this you know element. In fact, they probably have to be, if I'm guessing uh correctly. Anyway, so we'll get into the actual um algorithm here. So uh we start out with the fact that now we're storing the output from our last render phase. Now, what do we do with that? And this is where we get into the the you know the details here, I guess. So think about it this way. Every time we call render on our tree of components, we produce uh output result, which is a tree of elements, right? And now let's say state changes in between our renders. We're gonna have two different trees, right? So this is actually not a unique problem in computer science at all. Um trees are we use trees as a data structure all the time, and comparing trees and seeing how they differ is not a new computer science problem. Um there's been lots of research done into it. Um, but that's essentially what we're we're trying to do here is we're trying to take two trees and figuring out where they differ. So if if a button was there one time and now it's not, like how do we figure that out and then update what's in the browser to match? That's essentially all reconciliation is is comparing diffing trees. That's that's what it is. Um the interesting thing is so far um the fastest that we can do true tree diffing is uh O n cubed or n end of the third, you know. So that is um if if you're not familiar with like that type of notation, it just means that um for every uh element in our tree, we're drastically increasing the amount of time it takes to run the tree diffing algorithm. Um like that a very it's very, very, very resource intensive. Um and so React was like um that's too resource intensive. We don't want to render our our entire tree every single time, or even part of the tree, and compare and run a true tree diffing algorithm. Um so that's a that's like probably the key thing to know about why React works the way it does. Um you could have a true tree diffing algorithm, and if you did, a lot of what we know about React would be either very different or wouldn't need to exist. Um I'll get into that on the next part, which is React instead developed a heurustic algorithm that runs in ON time. So basically, if you have um you know 10 nodes in your tree, it takes time 10. Whereas in the you know, true tree diffing algorithm, that would be 10 to the third in terms of how expensive it is. So React is like doing it very quickly, but the way they do that is via their own heurustic algorithm that tries to guess when the tree has changed or when it's different. That's all it is. React is at its core just an algorithm for trying to guess when trees changed and updating the DOM to match. How does that sound to you, Austin?
It sounds pretty hacky in of itself. Um it reminds me of like the JavaScript language in general. Uh, I I think we've had these discussions before, and I've had them also with other prior coworkers, where like a lot of these features and functionalities have existed in highly refined effective forms uh for years, even and it's like the whole JavaScript community is like maybe they've come across these features in other languages and they're trying to recreate it now in JavaScript, uh, or they're like realizing that oh, we've we've recreated something that already exists and now like we should probably look back to the past about how it was done effectively and then like rework what we've done. It's it's kind of a recurring theme, I think, in this community.
Yeah, uh it definitely is, um, which I think makes sense based on how things have developed, but you're you're absolutely right. And I think to me, this ties into not not full, this isn't the full explanation, but it definitely ties into in a previous episode, um, I think when we were talking about hooks, and I was like a big part of the problem is React is too slow, and this is part of what I meant by that. Um, and that is if React was running a true tree diffing algorithm, um we would not have to do a lot of the things we do. So, like, take the best example is um actually now I'll talk about I I should talk about the actual heroustic and stuff first, that'll help it make more sense. But, anyways, um so the herous is based on two major parts. So the first part is that elements of differing types will yield different trees. So that's one assumption that the herous stick makes. So that means if your component originally returns a div and then next time returns a span, React is like, yeah, we're gonna have different um trees. So it's it's we have we have a difference, it's detected the difference that we need to handle. So this and the second part of the algorithm is um you can hint at tree changes with the keyprop. So this is also something that I think people sometimes find mystifying is what is the keyprop? What what should I set it as? When do I use it? Well, now you know it's a part of the reconciliation heurustic algorithm that um I guess you don't know how to use it yet. We'll we'll get to that, but now you know why it exists. It's a part of this algorithm, and it allows you to allow React to spend less time comparing trees by instead relying on the user specifying this keyprop. So if React had a true tree diffing algorithm, there would be absolutely no need for a keyprop. It only exists to help React's diffing algorithm run faster. Um I I bet you didn't know about that one, hey Austin?
No, I did not. I uh I knew that the the keys are quite important and I've only ever really added them on like list object, uh list like list iterations and stuff. Uh, but it seems that adding keys everywhere would be like ideal to really help take off the load of React. Um yeah, and I actually was running into this yesterday where I I had like a iterable uh like a list item, and I have like the key uh defined inside of that single list item uh component. And it was just making me think like how to kind of standardize and ensure that keys exist on every component uh that's created to to in a in a way that wasn't like annoying, like always having to write key equals something and come up with like a key name. Um still still thinking about that one.
Yeah, I mean I to me that's like a a problem that I would want to see solved at a different level of abstraction. Like I think having to specify keys is is only a performance hack, basically, and I would love to see that you know either get auto-generated or not need to exist or have that just get moved. Because I think that's a burden on it's a it's definitely a burden on the programmer that has no useful effect for them in what they're doing. It's just sort of like busy work.
True, true. Yeah, I mean it it makes me the the thing that uh I feel like the the bottleneck is with automating the creation of keys is perhaps like when like you're you're loading data from a server uh and you have like a key set with that item's like unique ID. And uh I mean I feel like that should be stored like on the initial first snapshot automatically. Like, hey, there is this somehow it's smart enough to be able to read that object uh that's printing into uh um an element, and it should be able to like internally create an actual unique ID for it.
So ultimately you're you're moving that some part of this tree diffing algorithm into user space and doing it yourself. So I don't think it actually ends up being a benefit. Um and that's like really the well, we'll how about we'll talk we'll talk about we'll definitely talk about the keyprop more later, but I think it'd be better to like explain how it's used, and then we'll be able to you know talk more intelligently about what to do with it. Um so that's the the next part of this, which is updating our initial render method that we talked about earlier for this reconciliation algorithm. So the first change we would make is we pass in, or I don't know, maybe we already made this change, we pass in that tree that we stored from the previous render, we pass that in. Or if it's the first render, you can actually just pass in like an empty object element that doesn't have anything in it, and the algorithm works the same. Um but basically it runs through four things. So first um it looks to see if it can re- it first it looks at the DOM node types. So it's like, okay, I got my two trees, are the types the same? If they're the same, I will reuse the existing DOM node.
So pretty simple, right? Um and and if they are, then it will update the DOM props if it's needed. Um so React is um somewhat intelligent about only updating props on a DOM node if they need to be. And this is important for what we talked about earlier, which is maintaining like browser state and stuff like that. Um so it is intelligent at the updating of DOM props. Um and the next thing is uh render, you know, to note about this algorithm, I guess, is that the reconciliation algorithm always renders all of the children of the element. There's no like like sidestepping this. It's always going to call render, like pass the children to this render function. Now if there so so where the key comes into place is uh you can say you have a list of elements, right? And let's say you add a new item to the list. Well, by default, like if we didn't have a key, what that would mean to this reconciliation algorithm is that we need to delete all of the uh or we we might be able to reuse a DOM element, but we're at least going to be updating every single DOM element potentially in that list with any like props that have ch changed. I didn't say that very clearly. Like let's say we have a list of five elements, right? And maybe they're all divs even. But let's say we add a new element to the front of this list. Well, now our old tree and our new tree don't match up because the the number of elements isn't the same. Um and like your last element is gonna be non-existent in one case, and it's gonna be an item an element on the other case, and so it'll run through this algorithm and it might be able to reuse the DOM nodes. But if the props themselves are different, it's gonna be updating a bunch of props, blah, blah, blah. You know, like um when it might not need to. Like it might be in general is doing this unnecessarily because all we did was you know add a new item to our list. That doesn't mean we need to redo all the other elements in our list. Um, and so I'm guessing what happened is initially React didn't have this feature for keys. And what they found was that when you're like inserting and removing items from list, it was causing like you know, a hundred or two hundred or ten thousand items in your list to be um re or to be re-updated in the the DOM and the browser, which was horrible performance. So they said, well, what can we do to handle this? And they're like, well, we'll create this key prop. And if the keyprop matches the keyprop of something else in the list, we won't touch it, you know. Um we'll we'll run the same algorithm over it if if like your I actually I don't even know if they do. Um but basically they won't touch it. So like you can move things around in the list and React is like, oh, the key in position one in one tree matches the key in position four in this other tree. And so I know that I can either update that same DOM node or just leave it the same because the keys are the same. Now, if we didn't have keys, like I said, you would not have that benefit and it would be re-updating everything in the list. So so a key is just like a way to help React know how to match up elements in the tree without having to go through and try to manually do that using a true tree diffing algorithm. So I don't I don't know. Did any of that make sense to you, Austin?
Yeah, I get it. The whole thing that I just keep coming back to is like that auto-generation of keys and like how uh how React could even truly uh intelligently establish a unique identification of things based on like changing data. But yeah, uh, and it also makes me think about how they've been trying to bring in stuff like lazy loading and suspense to help like alleviate some of this uh this pain. I was wondering if uh that's part of what you want to go into with how how those features have helped with this process mitigation.
Um I so Lazy loading and suspense, I don't actually know that they do help at all. Other than they could potentially prevent part of the tree from existing. Um that's like um probably my biggest like key sort of takeaway from all of this is if you understand how this algorithm works, you will understand that um once you start like like controlling when parts of your tree actually get rendered is the biggest and most critical um performance thing you can be aware of. So what what do I mean by that? Well something I haven't mentioned is that React doesn't need to render the entire tree every single time, right? And and we all know this is the case. It doesn't render the whole tree every time anything changes. What you probably notice is if like you part way down in your tree, you have a component with use state or some some kind of state changing thing in it, and you change that state, what you'll notice is React starts rendering at that component. Now, the the key thing there is it still follows this algorithm, and that means that everything below that component in the tree absolutely will have render called on it. There's no no way around it. Like once you start rendering part of the tree in React, it is gonna render everything below it, and it never stops, nothing ever makes it stop, except returning a value. So this is where like when people talk about any like performance-related things, this is the number one thing that uh they need to understand first. Is the easiest way to improve your React performance is figure out where a bottleneck is and then figure out if you can prevent that part of the tree from getting rendered so frequently. Because if you do that, you will automatically just fix your problems without even having to like optimize any code in a component. Um and the way that you do this is by memoizing components. So I see people doing like use memo on like data or arithmetic or something, um, that type of thing. That's not really that that's not where I would usually look to add memoization. React provides APIs to memoise a component. Now, what does that mean? That means um React will still call render on that component, right? But since it's memoised and if your data, your input data hasn't changed, React will just return the last value of the render for that component. It won't actually render that component. So you can effectively prevent React from rendering entire parts of your tree. All you have to do is properly memoise your components. Um I think I don't see a lot of people using this, and I think it's because they don't understand how React does things, and so they don't see that that's really the right place generally to you know start making performance optimizations. Is is that is that new new news to you, Austin?
Well, the yeah, the I I have not actually done React.memo on a component ever. Uh myself, I've used the use memo uh hook to memoise uh large data sets that I bring in, and I I've seen that help. Um could you go into like a the simple API overview of how React.memo works, uh wrapping your components in that. It seems pretty simple.
Oh yeah, it's super simple. It's uh basically you pass in your component and then you pass in its dependencies. So um these are the the dependencies, the things that React should watch for to change. Um and you don't need to pass in internal state. React will handle that for you. So if internal state changes, React will re-render your component um and not return the old result. Um but otherwise you you don't really have to do much, just list out like I don't even know if you have to list it out. You might not even have to list anything out. I think that's actually a performance optimization. Because React knows what your props are and it knows what your state is. Um the thing that React doesn't know, and this is why it doesn't do it by default, is React doesn't know if your code has side effects. So as long as your component doesn't have side effects, um, which means as long as the state and the props in the component always produce the same output, like the same props and the same state always produce the same output, you can memoise any component like that. Um and it will work great. Uh so that's really all you need to be aware of is that you're you're not doing side effecty things in your component. If you aren't, then you're golden and all you have to do is wrap it in a React memo. Uh there's an API both for class and function-based components. And if you do that, um, yeah, you'll have generally much, much better performance. Now, like always, I don't suggest necessarily doing this all the time. Um it's still better, in my opinion, to wait until you have a performance bottleneck. So, what I do is if I have a performance bottleneck, I find out which component it is in, and I see if, okay, this component is a pure component, it doesn't have any effect uh side effects. Um, then I wrap it in memo. And usually or usually that fixes it. Maybe, but maybe you can even go higher up in the tree. So I'll look at components higher up in the tree and see if I can um wrap them in a memo and prevent the poor performing component from getting actually called unless it actually needs to be. Um so that's usually the way the approach that I would recommend taking.
So, like a real, like a real world example of how to use like memoization of components would potentially be like trying to really create like business logic components that handle all of your state effects, reducers, whatever, any hooks you do, and then passing that to a memoised, really stupid component that only accepts props and doesn't handle any internal state. Component library stuff could be memoised, for example. Would that would that be smart?
Yeah, no, you're so basically what you're saying is somebody on the internet said you should break your application. That's that's actually what it's what you're saying. Um because if you have state affecting things, or if you have not state affecting things, but if you have state that can change in a component, um you should be probably re-rendering anytime that state changes. Otherwise, what you have in your React code is not going to be reflected on the screen. Um so the right way to do it is to just memoise that component. And if it if it um you know, so it so it should work perfectly fine. Just memoise it with all of its complicated state changes or whatever, it'll still only um have to rerun its render code if something has actually changed since the last time render was called. If something has actually changed, then you should always be rendering. Although, I mean, maybe there's some weird case where you're not, but that's probably not very good code, I would suspect. Does that make sense?
Yeah, that's what I was gonna get into. Is the the downside is memoizing is still um caching and it still adds complexity to your component. Um you know, maybe somebody later on it doesn't realize you've memoized a component and they add some side effecting thing to it. And now they deploy it and then we're like, hey, why isn't this working right? It's behaving really weird. Sometimes it seems to work right, sometimes it doesn't. Um, and that's that's the the risk, I guess, of memoizing something is it you can't always predict how other people are gonna use the code or even what you're gonna remember, you know, a year later or two years later. And so you run the risk of introducing bugs. Yeah, a week later. Yeah, so that's like it it I think it is actually generally pretty low risk. Um, so it's not like I would be opposed to some sometimes using component memoization um proactively. Um I think of this especially for like say things, especially things that contain lists. Um, like say you had a a tab container component, you know, that has a bunch of tabs in it. Um I think it would make a lot of sense to use memoization in that case, so that um anytime some state changes, you're not re-rendering all the tabs. Um there's there's like um yeah, sort of like that that level of abstraction I could see um doing it preemptively because you're like, I know that it it's gonna nobody's gonna come in here and modify my library to add side effecting code, and I know that this is a beneficial case because somebody could have a hundred tabs open with a bunch of different stuff in them. So I I could see cases like that doing it. Um, but if you're like looking at actual, like just you know, business logic components or whatever, I I don't know that it's worth the the slight amount of risk to do it up front.
And you were mentioning that like uh some things like they could update it and then it's not working as expected. What are what are some uh like in your experience, some of these things that are like unintended like side effects of it not working properly? Like it will it won't re-render the way you expect, or like what what kind of things have you run into where you notice like, oh, it's not it's not working now?
Yeah, so what you'll run into is um what is displayed on the screen or the behaviors on the screen or whatever are out of date from what's in the component. Now, what that means in terms of in in practice depends on the component. Um but it it just means that you're circumventing the whole benefit of using React. Like without React, you have to manually keep your state in sync with what's on on screen in the browser. Um with React, it handles that for you. But the only way it can correctly handle that for you is if you follow its rules and assumptions um for this reconciliation algorithm. And so if you start breaking those rules, all it means is that you get your state out of sync with what is what I assume you want to actually be on the screen or the behavior or whatever. Does that make sense?
Yeah, so it's um yeah, so that's why I I think I tend towards just not adding memoization unless I I find a an actual need for it. But um I think it's the the number one by far, in my opinion, that and keys, we'll which we'll still talk about, are the the two the two most important things to um look at first when you have performance bottlenecks. Um so first thing I always look at is um memoization. Can I memoize some part of this tree effectively and have things continue to work right? If I can, I'm eliminating the the bottleneck, you know, generally. Um there's there's actually um there's there's some interesting things though that I should note about this. The number one thing is, and this is a question that I've gotten, is oh, but if we use memoization, aren't we gonna fill up our memory uh with all of the old states, you know? Um because typically in memoization you are basically using a hash map or something to store your inputs to the outputs so that you can look it up and and return them. Um React only stores the last um input and output. So it's not even, in my opinion, I I kind of don't like how they called it memoization because it's not true memoization. Um I guess we're learning a theme here. React doesn't like true things, no true tea tree diffing, no true memoization. But anyways.
Yeah, yeah. There's like the the best level is called Truth and Reconciliation. And I just I've been waiting to drop the nerd reference. Because I the other day I was at Walmart and I bought I was walking through the coffee aisle and there was a Master Chief uh coffee mug, and I was like, oh my god, if I don't buy this, like I will never see this again. And hit Master Chief's been staring at me this whole episode. I had I had to drop the nerd stuff. Sorry.
Uh yeah, I'll just finish with that is like something to be aware of is like um if you're adding memoization to something, you need to keep that in mind. Like if your component is alternating between two different states, memoization will have no positive impact at all. Um so there are other caveats to memoizing things.
Absolutely. Yep. It it's yeah, so it's not unfortunately not as simple as we might want it to be. Um, but it's definitely the thing I look at first, um, and it has always been the most beneficial to me in solving any kind of React performance bottleneck. With the only other exception to that being our next subject, which is the keyprop. So the keyprop, and I will note um right up front, the keyprop doesn't even have to just go on lists. Um I I don't you probably haven't noticed this, Austin, but in I actually do use the keyprop on a non-list item. And the reason for that was because I forget if I did something wrong or some component, I think some library I was using did something wrong. But React was not um re-rendering the component every time it should have. And if you add a key prop and the key prop is set up properly, then you will get around that issue. Um so I don't know if that's something you've ever seen before.
Uh, it's only something I've seen a couple times, but uh yeah, well that that's where this topic came up. Uh I mentioned earlier, is I I found that well, yeah, the the ESLint plugin we use was was complaining to me about not doing keys on stuff, and I I started thinking about the whole key thing a little bit more in general, and I was we have so many things that like you have say you have just like some random typography element, like is that theoretically getting like it has to run over that and determine if it should re-render, and if I added a key to that, would it know quicker just to skip it?
Um I don't know actually. So I I know that if you have a key prop and the key changes, it will you know re um update that component or resync that component with the DOM. Um I don't know about like if it stays the same, if that matters. I'm actually not sure. Um but I I can tell you about what I do know about the the keyprop, and and that is where it's uh most commonly used is lists. Um and that is a warning people will often see if they don't include it in lists. Um and the reason for that is if you go back to our conversation about memoization, um memoization it can basically solve most React performance bottlenecks except for lists. Um because like how do you like the only way to for memoization to help you with um a list of a bunch of elements is to memoize the parent component so that it never needs to re-render all of the elements in the list. But if your parent component has state that changes, but maybe only one element or one item in your list changes, or maybe the list itself doesn't change, generally it's you know, something in the list has changed, just not the whole list. There's no way to use memoization to speed things up or make things better. There's there's no um real solution to that. And so React, I think the team had to add sort of an internal um hack to uh allow us to give hints to the reconciliation algorithm. Um but the the important part is if you want it to work well, you have to specify keys that actually make sense. So, what do I mean by that? Like something that you might have seen is when people um are outputting a list of elements, they'll do like um key equals you know I, which is the index into the list. Um and that is a basically nearly worthless key.
Yep, absolutely, totally right. Yeah, your key needs to um be a unique and b persistent and And C needs to change anytime the underlying data changes for that list element. So those are the things to keep in mind. So unique is pretty obvious. If it's not unique, React won't be able to run its algorithm effectively. If it's not persistent, and persistent by that I mean every time I render the same thing in my the same list element in my component, it should return the same key. So I've also seen people that are like, oh, my keys are like you know randomly generated numbers or something. That also doesn't work because React can't the you know the keys will never be the same in the two different trees that it's diffing, so it's literally no use at all. And it's gonna have to re-render everything or or at least um resync everything to the DOM, even if it was not necessary. Um so that's really important that it's persistent.
And then yeah, I did that when I was uh when I first started programming. I was like, oh, keys need to be unique. I'm going to literally like create a new UU ID for uh each of these things, and I like had this list with like the function calling to to create a unique ID, but each time it was re-rendering, it was creating a new uh a new ID. And I was like, wait, this doesn't work. So in theory, it it's actually if you use non uh consistently unique keys, you're actually creating a performance hindrance because you're like confusing React and it's like, wait, like it goes to search for the key and then it doesn't exist, and it's like it's like okay, we gotta start from scratch now.
Right, right. Well, I mean it it it theoretically could be like I mean it's like death by a thousand paper cuts if like you have this huge list and you have like some key that it can't find anymore, it still attempts to like find it, and then when it can't, it just skips and goes to what it should have done when it didn't have a key, right?
I don't think so in a in a technical sense, like if I was writing a tight loop in C and all it did was lookups like this, then yeah, but in the context of a larger React application, I doubt it will ever be noticed. That that lookup itself, you know, not specifying the key correctly, that will absolutely be noticed.
Yeah, so and um yeah, so if you're creating your keys, just you know keep those things in mind. And and if you do, um you'll get the optimal performance of the reconciliation algorithm. Um React will be able to most effectively sync your internal state to the browser, and that's what we want. So, you know, um that that's really all it comes down to is React has a heuristic algorithm for reconciliation. And if we understand that algorithm, we can understand how best to aid the algorithm, and that's really important, especially for heuristic algorithms, um, which are you know sort of less concrete in how they behave, um you know, rather than like a tree tree diffing algorithm. Um but yeah, so I think that's actually like um pretty much the the whole thing. It's uh it's pretty simple. Um it's it's uh looks at um in fact I can even um I'll just like run through it in summary real quick here. So like um let's say we have our render function, the first thing we do is if our new element is not specified, but we had a previous element in the tree, that just means that the we're we need to remove something. So we remove a DOM element and we look that up from the old tree and just remove that DOM element, which would remove the entire tree of DOM elements below it. Um then let's say that doesn't that's not the case we're looking at. Um in the next case we test to see if our new element does not equal our previous element. Um and if it doesn't, then we need to create a new DOM element. Or in the next case, let's say if our this is where we we've talked about before, if our element type is equal to our previous elements type, then we can reuse that DOM element. And this doesn't mean like that this could be two completely different components being rendered in returning a div element. That's fine. React will reuse the div element, even if it was originally created for a totally different component. It doesn't care. It's like it's a div and it's a div where I want it to be in the tree, so I will reuse it. Um but let's say none of those cases matched. That means our element in the tree and in our previous tree are of different types. So that means maybe it used to be a div and now it's a span. In that case, we have to remove the previous DOM element and all the elements attached to it, all of its children. So we remove all of them from the tree and create a new one. Um and then we will use that new one to attack to you know render its children and build up a new tree. Um so so that's sort of the the very basic um version of it. Then you have um you set your DOM props on your new element or your existing elements, whichever you've selected. Um and in its um, like I mentioned before, React is uh does have some intelligence in terms of like making sure to update props correctly. But I think it's interesting to note here that that means you could have like you know a div with a class name prop and some event handlers or whatever in your previous render. And maybe in this render we have a div with you know just some style props. React will reuse that div and remove the props that are no longer needed and add in the new ones or update the ones that are the same. Um, and then after that, we render our children. So we do this same process on our um each of our children. But before we do that, we perform a basic analysis to see if we can reuse or reorder the way in which we do this so that we can reuse these DOM elements. Um and that's that's the whole uh key thing. And then the last thing is if our if we need to add a new element to the DOM tree, like we're not just modifying one that already exists, then we add it to the DOM tree and we're done. We have gone through the entire render process. You now know what what React does under the hood.
I mean, this whole episode has been rather enlightening. Uh, I I feel like it was uh that you mentioned your book earlier, the one that we have available on the website. If you sign up for our email list, you can get for free the foundations of high performance react. It seems like a really good complimentary episode to that book, uh, a much more in-depth uh dive into things. And uh I already feel like I've learned a whole lot more today. That's what I love about these podcasts, is every time we get on, I uh I'm either learning a lot from you or I'm asking you questions that you can't answer that next time you're like, oh hey, I figured out the the that, and then it's like more learning. So really, really great episode today.
Yeah, no, I love it. Summarize what we talked about today. So we looked at um create element um at a pretty broad level, you know, JSX compiling to create element objects, um, which have type and props, including children. Then we looked at the render function itself. How does React take the output from your component and create actual DOM elements on the screen and attach them and things like that? Um and then we looked at reconciliation, which is React's algorithm for figuring out which DOM elements to update, so it's not replacing the entire DOM tree every time anything changes. Uh I think um if I think I don't know, I had a lot of fun doing this. Um it's something I've studied obviously and and know a lot about, but even you know, just talking through it again, I always feel like I'm learning anyways and and um understanding more. Um so yeah, if you uh had any more questions, definitely let us know. Um, direct show at owlcreek.studio. Um and we did actually have um a question from someone on Twitter, which I thought tied in. Um and so this was from Lance Klinger. Um and they were saying, I would like to know if there's a good alternative to calling a set state inside a use effect. My understanding is that causes a re-render and could trigger a different use effect and so on. Is there a pattern or patterns to flatten this flow? Now I know um Austin might have some thoughts on part of this because we've talked about it before. Do do you want to start us off, Austin?
Well, yeah, the the one thing I uh I was doing a lot where I I was doing these uh set states to then trigger uh another use effect to listen to uh to that set state to run run another thing, and I I started to just use the pattern of trying to avoid having to use the use effect um and just doing the logic I need inside of the callback function that was uh triggered by the user interaction. Uh and I found that that reduced uh at least one or two side effect renders uh pretty pretty easily. Uh but other than that, I I would love to hear your thoughts.
Yeah, that that's exactly what I was thinking of as one of the most common cases is um people are using use effects to set state when it's just not necessary. Um you could look at where um like so the the reason why I I said that to Austin initially when we talked about this is because a use effect runs generally, people set it up to run when a few variables change, you know. And if what I would look at then is when does that variable change that you're that is causing your use effect to run, which is causing you to do the set state, can you instead move the set state to wherever you've changed that you know, presumably internal state or prop? Um and oftentimes you can. Um so not always. And I think it's actually a really interesting question because it's absolutely true that every time you render your use effect will you know be queued up to run if you're not using the dependency array, or potentially run if you are using the dependency array. Um now the thing I would ask is is this really a problem? Um there's like the like I think the approach we were talking about earlier about moving your set state closer to the source of where it sh could be and is you know closer to its initial trigger. I think that is like a just a cleaner code, it's better code. So that makes sense to do, anyways. But like let's say we're not talking about that case, but just in general, you know, is this a problem? Well, um, like they say at the very end, it could be an actual problem if you do something like this, where you set you your use effect gets triggered, so you set state. And that state that you've set triggers your use effect to get run again, and then so you set state again, and that triggers your use effect to you'll usually usually this is an infinite recursion and you'll run into an error if you do things like that. Um, I maybe it's possible you only do that chain a few times in a row. Um I'm not sure if I run into that case, but I could see that happening. Um but I would say in the general case, like I I wonder why you're asking this. Like, did you run into a performance bottleneck or something? Um, because if not, I I don't know that it's necessarily a problem. Like um a re-render is not necessarily a problem. A lot of people talk about that with React, and that's why I wanted to bring it up in this episode is we have talked about re-renders and reconciliation, how all this works. You know, is it a problem if we have a re-render? Um I don't what do you what do you think, Austin? Is it a problem to re-render?
I mean, unnecessarily, yeah. Like the like we talked about you like uh re-rendering with the set state and then having a side effect one that then triggers maybe one or two more, that could be problematic, but ultimately uh if you've constructed your your application and your elements properly, the the reconciliation will take care of handling it uh intelligently, right?
Yeah, I I was gonna say the same thing as like I um I would be hesitant to consider re-rendering itself to be a problem. That's you know, React is made to handle re-renders. That's why they have a heuroustic reconciliation algorithm in the first place. If we only re-rendered our tree like super infrequently, and if there was some way to run this algorithm maybe in chunks or in parallel, there would be really no issue. Um it's just I don't know. To me, it's like React is made to render components. That's what it's done. If you have a problem with re-rendering, the we go back to what I said earlier. Look at memoization first. If that doesn't work, then yes, maybe I don't know, something weird is going on with your used effects and and you need to figure out a better flow or a better pattern. Um but I don't know that that's really that necessary. Now let's say I don't know. My problem with answering this question is I can't even think of a case where this would really be a problem in which I solve it at this level. Like if I ran into this, I would be looking at other levels probably initially. Like, hey why is my use effect being run like in the first place, or can I memoise things or whatever? Like, I I don't know that um it's that much of a problem, but maybe I'm just missing something. So I don't know if you've ever run into anything, Austin, but I'm not thinking of any other cases here.
Yeah, I mean I've had a case where where this has happened where uh uh the a use effect setting state then triggers like uh multiple other side effects, or yeah, like you said, getting caught in a re-render loop and then it crashes. Um, but it it makes me think about how we talked about writing uh the the way that we write a component a little bit more uh in a in like a different paradigm. Like, for example, we have like uh we're using that query in the way that like it um as the re-render goes through the component uh to get to the the actual return, um the those hooks and stuff are conditionally modifying the way that your component works uh in in a different way completely. It kind of hard to explain as I'm still wrapping my head around like different ways of flowing data down into your component. But I like talked about it with uh how you remember doing the uh the loading example the other day, uh the more imperative approach to it. So maybe maybe that would be something to go a little into.
Um get in touch with us uh a little bit more about like uh specific use cases that you're curious about, and we could we could chat about that a little more and uh do a little learning deep dive. Uh and yeah, we'll we'll go ahead and look into doing another episode on some higher level paradigms that could reduce your need to even consider using use effect, right?
Yeah, I would love that. I think that that would be a great topic because certainly something I think needs to be discussed. Um yeah, so uh I think we'll we'll wrap it up. That's uh all we got for today. Um yeah, I'm uh your host, Thomas Hince, with my co-host here once again, Austin. Um and yeah, if you have any feedback or or questions, you know, once again, feel free to email us at the React Show at all creek.studio.
