Learn the fundamentals of React by working through its mechanics from how the browser loads React, to JSX, components, state, rendering, & reconciliation!
- My Book - Foundations of High Performance React
- Consulting: https://thomashintz.org
- Norris Sea Slug Photo By https://www.inaturalist.org/users/passiflora4
- Music by DRKST DWN: https://soundcloud.com/drkstdwn
Thomas Hintz: And welcome to the React show!
Brought to you from occupied Miwok territory by me, your host, Thomas, and some fruity Chiapas coffee, Episode 87.
Are you ready to learn react quickly, and methodically? In this episode, we go through the entire mechanics of React, from how it gets loaded, to how your components actually run. We learned how to program in React and how it all fits together in a structured way.
Thank you for joining us! So I was out tide pooling, of course, near La Paz, in Baja California Sur Mexico, and I met a new friend. It was actually incredibly remarkable, because they actually wanted to learn React.
So I asked them to join me on this episode of this show. So we could cover the mechanics of react together.
All right, so hi, Norris. Welcome to The React Show.
Norris. Hey, Norris! I know you normally live underwater, but you have to take your head out and speak into the microphone, or nobody will understand you.
Oh, all right. Sorry about that. I just wanted to say hi, and thank you for having me on the show.
Yes, that's correct. Yeah. So you know, being a sea slug out here and the rocky reef of Baja California. We're a little bit you know, it's a little bit slower some of the the latest technology and making it to us. Just just by nature of being a slug, and I don't know, maybe we're slow at building our internet infrastructure. I don't know.
But hey, I've heard about React. And so what's really been going on is I built a simple website in HTML and CSS to showcase upcoming music events at the reef. And there's this burgeoning underground rap scene developing. And I really wanted to highlight some of the awesome new artists that are joining the cruise.
Wow, that sounds really cool. Norris. Congrats on launching the initial site. Yeah, this sounds like a potential application for React. React is good at handling complex state and logic in a way that eliminates some classes of bugs. Why don't we first start with a quick overview of how web pages work and how react actually gets loaded?
Oh, yeah. Okay. Yeah. Thomas, that sounds great. So to be honest, I have a rough idea. But I find like I have a rough idea of of React. I mean, I sort of looked, I spent like an hour looking at some react documentation. But I find learning more about the mechanics of how something works helped me just helps me understand how to use it better.
Yes, exactly. Sounds simple. But I imagine it's a lot more complicated underneath. i If I've learned anything about computers and programming at this point, it's that everything is more complicated underneath. But anyways, I'm curious what what happens next? How do you actually include in run your React program?
Hmm, Ah, okay. That kind of makes sense to me. But what the heck is a DOM element? And how do you pass in a reference to one seems like you're speaking in a foreign language here? I mean, come on. Here, Thomas.
Alright, great question. I don't want to be speaking a foreign language to you here. So a DOM element DOM standing for document object model just means one of the HTML tags that you included in the HTML document that the server sent to the browser.
Yes, exactly. There are a number of functions you can call that browsers provide that will allow you to get a reference to one or more of the elements that you see on the screen.
Oh, okay. Sweet. So we grab a reference to this kind of container element, and then pass it to react createRoot. Is that correct? I mean, what what happens after that?
Yes, that is correct. After that, you need to call the render method on the return value from createRoot passing in a React component object.
Wow, Thomas. That's a lot. Alright, so we call the render method. That makes sense. But can you elaborate on what you mean by a, quote, React component?
For extremely simple interfaces, this works fine. I've done it many times before JSX, before react, and it works. But for complex UIs, with many nested elements, is very, very hard to read and work with as a programmer. So instead, you can use JSX. And write these HTML like tags, like it'll feel like you're writing HTML pretty much. And you can just write a button tag very similar to how you would do it in HTML.
Yes, absolutely. You got it. Correct. You follow along so well!
Yeah. Okay, great. So then you're saying I should use a different programming language called JSX? And that goes inside of the call to the render method?
Yeah, exactly. You got it Norris!
Okay. I think I'm following. But what about components? I thought react was all about components. What are components? You haven't said anything about components yet? Are you even talking about React?
Indeed, you caught me.
So the truth is, though, you can actually write a React program without creating any components, you can just pass in objects to the render method that describe plain HTML elements, like you do when creating a regular HTML web page. Essentially, you can use React to create web pages that look just like the web pages you would create in plain HTML. And if you use JSX, then the code will even look very similar to plain HTML.
What? Are you kidding me? Wow, that sounds awesome!
So for example, if the browser's don't have, like a calendar, HTML tag, I could create my own in React, and then reference it in the JSX. And it will just show up on the screen. Like I've created my own new HTML tag?
Yes, you've got it, you can totally do that. It's pretty cool, right?
Yeah, I can't wait to give this a try. So you're saying I could create this calendar tag or component, and use that on the page for people to click on to select when they want to book their favorite underground artist? What if I want, though, to be able to control aspects of the calendar like, say, gray out days that has been sold out? Do I need to create a new calendar component for every single use case for every single concert? I mean, that sounds like a lot of work.
That's a great question Norris. And the answer is no. And this is where react really starts to shine. So you know how with HTML tags, you can set attributes, right? Like the type of an input or the class name. Well, you can do the same with React components, you can set attributes, which in the React World that we call properties, or you'll often hear props for short. And react will pass those to your React components as function arguments.
Huh. That sounds cool. I'm not quite sure I follow yet. Could you just elaborate a bit more on that?
Wow, really, I can't wait to do that. Sounds like I can use these React components to create my own HTML elements and pass data into that is, that sounds really exciting. I'm going to find a large rock to crawl under here and give that a try. But before I get to that, I was wondering, what did you mean by render? You've said that I think a few times now and I hear that a lot with React. But what does it really mean? What does render mean?
Oh, I love talking about rendering. But unfortunately, before we do that, we should talk about one more thing and well, okay, I say one more thing, it might be a few more things. But the first thing I want to talk about before we get into rendering is state.
It's cool to create your own components, right. But they, I promise, you won't be very useful without state somewhere in your program. And state just means a way to store and retrieve information basically.
For example, with the calendar component that we're talking about, let's say you want to allow the user to page through months of the year. This means that somewhere you will need to store which month the user is currently viewing. So when your component renders, you know, which days to render in the output for the user, right? React actually provides multiple mechanisms to do this.
The simplest is what is called the useState hook. It sounds scary. I know, I know, I can see you over there Norris sort of flipping out there as you slugs do sometimes. But I promise you, it's pretty easy to use at least this hook.
All right, yeah, you're right, that it would be your first instinct, and it would feel the most natural. But this is where we start to get into the whole render thing. So remember how components are just functions that we've defined? Well, these functions should be programmed specially, so that they don't have any direct side effects.
But the important part is that you use these hooks for managing state and this ensures that your React program will work correctly, your React components should always be what we call in the programming world. The computer science world we call pure, pure functions, can transform their attributes and properties, their arguments and state to output JSX but they can never affect anything outside of the function.
You can think of pure functions and pure React components as tiny little isolated programs inside of your larger program.
Okay. Okay, so to make sure my program works correctly, I need to make sure that my React components don't modify or read from any global variables. Am I getting that correct?
Yes, yes, you're right. You're getting you're quick at this. I'll be honest, that is correct.
All right. So you're saying for storing the current month the user is viewing, I should not store that in a global variable, that my component reads? And sets, right?
Yes, again, correct. Think about it this way. What if you wanted to use your calendar component in multiple places on the same page? How would you actually store state in a global variable? Would you create a new variable for every instance of your calendar on the page? How would that actually work?
There are ways to make that work. But what if instead, you use the state hooks provided by react like you state, if you do this, react will take care of that for you. You don't need to worry about it. You can include as many calendar components on the page as you want. And you won't need to keep track of the state in some special way to make sure that one instance of your calendar component doesn't affect the state of another instance of your calendar component. You can just program the component like it lives in total isolation.
Ah, I guess that makes some sense. So this hook and state mechanism allows me to program my components in an isolated way so that I can include as many as I want without having to worry about them interfering with each other. I mean, that's what it sounds like, right?
Yeah, exactly. Right, Norris. Hmm, that sounds a bit complicated. I'll be honest. But I guess I can see the advantage. Okay. I think I got that under, under my my gill here. Does that now mean, we are able to talk about rendering finally?
I think we're very close to talk about rendering. But I want to cover two more things very quickly before we get into that, that is events, and effects.
So inside your components, you can set up events, like let's say when a user clicks a button, you can set up a click event on that button. Oftentimes, inside of the handler for an event like that is where you will put your code that actually changes the state. So for example, if the user clicks the button to show the next month in the calendar, inside of the handler for that buttons, click event is where you would actually make the call with the use state hook to update the name of the month that the user is viewing.
Once you do that, react will run your component code again, in your component will be like, Oh, I'm supposed to be rendering may now instead of April, and it will render different days out to the screen and different orders or whatever it wants to do.
Yep. And the other thing to cover is effects. So sometimes you do need your components to have side effects, like maybe they need to make a network call. Well, you can't just put this code directly in your React components, because that would make them no longer pure, and you'll start to get weird behavior and bugs.
Instead, react provides another function called useEffect that you can call that can include code that has actual side effects. But using the useEffect function, you're setting up your side effects in a structured way that allows react internally to handle that code specially. So it doesn't create unexpected bugs for you.
It sure seems like React does a lot of special handling. For me, I can imagine I might use an event handler or use effect to then submit the network request when a user actually buys a ticket. Is that right?
Yeah, that's exactly right. You can have side effects in event handlers, or inside calls to useEffect. You can't put them in the regular main code path that you use to render the JSX output for what gets shown on the screen, but you can have side effects they just need to The inside of event handlers or calls to useEffect.
Alright, so now that we we have that covered, I think we've done enough to get back to your original question about rendering. So rendering is the process by which react runs the code for your components, and then syncs them with the DOM. Calling render the first time causes react to take the output from your components and actually converts them to the elements you see on the screen.
And as react runs your components for the first time, it also sets up some internal triggers, like events that can in the future, tell react to call your component again and get the updated output. So every time react calls your function that represents your React components, it is called a render.
So really, React is actually very simple. Like I said before, it just calls your component or child components over and over again. And a child component is any React component that you return in your JSX from a React component. So you can have a parent React component with multiple children React components. And so when you define a React component, you should just think of it as an isolated entity that can get called one or many times, and you don't have any, like direct control over when your function or React component gets called React is allowed to call it as many times as it wants, whenever it wants. This is another important reason why you shouldn't have direct side effects in your React components.
Ah, okay, I think I see, the way you describe it with child components makes it sound like a tree kinda. Is that a good way to think of it as a tree?
Yes, exactly. Your react program will be made up of a tree of React components.
Okay, I think we can now talk about the rest of the rendering process. So react starts by calling your top level component highest up in the tree. And that component returns JSX. That includes other components. React just works its way through the JSX, calling all the components that you've defined, eventually, it makes its way through your entire tree of React components, is left with just plain native HTML elements, like defined in your JSX, basically, like all of your React components eventually decompose down into HTML, elements of some kind, like, let's say your calendar component is made up of a bunch of divs, and spans and whatever eventually, by executing your React components, your functions. React ends up with a bunch of just basic HTML elements, right?
But how does it go from this tree of HTML elements to actually putting something on the screen. And what happens if a user triggers an event or state change? This is the fun part that makes React, React. And that is called reconciliation.
Now, it then reconciles this new tree with the tree it stored before and if it detects any differences between the trees, it updates what is on the screen to match the new screen. And this is if you have ever heard of like the virtual DOM in reference to react. This is basically what it's referring to this internal tree that React is storing and analyzing and reconciling that represents the state of your React application.
In fact, the earliest versions of React were much simpler. They didn't even have a virtual DOM, they didn't have these, it didn't store these trees. Instead, anytime there was a user interaction, or state change, they just deleted all of the elements that initially added to the screen. It then reran all of the code of all of the React components, and converted the output to what you see on the screen. Basically, it just reran the program over and over again, every single time there was any change, blew away everything on the screen and rebuilt it all.
And this is actually conceptually still a very good way to think of how react works. Technically, it's not how react works. And we're gonna get into that a little bit more. But conceptually, you can absolutely imagine that's the way react works. And that will basically cover all normal uses of writing a React program.
Okay. Okay, so I'm just a sea slug here. And this is a lot. Can you give me a chance to extend my gills and catch some oxygen? At least?
Yes, yeah, absolutely. It is a lot. You're right.
Okay. Thank you. Alright, so let me see if I got this. Right. So in summary, are you saying that I can just imagine that react runs all the code for all of my components, anytime some state might have changed? And then I imagined react, deleting everything that it added to the screen and replacing it with the new output from my React components?
Yep, conceptually, that's exactly how react works.
Huh. So basically, I don't need to do anything to actually tell the browser what updates to make when the user interacts with my calendar, react just kind of magically takes care of it for me.
What, wow. Oh, that's so cool. Now I see why React is useful. It sounds like it eliminates a lot of manual work, I would need to do otherwise.
Yes. And that also eliminates an entire class of bugs that you might crawl out from the rock next, you know, where you might make a mistake in that stage of your program, where what the browser shows on the screen becomes out of sync with the internal state of your program.
Awesome. Neato Bandito!
So that old thing about React, reconciling and storing trees and stuff is really just irrelevant. Like, why did you tell it to me? Do I actually need to care about any of that?
Okay, well, that is an astute observation, Norris. But the answer is, unfortunately, kind of I wasn't just telling you that for no good reason.
So remember how I said that initially, react didn't do this whole tree reconciliation thing and just reran all of your React code all of the time, and rebuilt the onscreen content from scratch each time. Well, that absolutely did work, and it still would work. But for complex applications, it is just too slow.
So react decided to make some performance optimizations to me render your React program react executes the code for your components and stores, the tree of output, like we talked about, after putting everything on the screen, then whenever an event occurs, or react thinks some state might have changed in your components, it reruns all, or at least some of your components code, your components, again, output this tree of nodes.
React then compares the new output. It's to the output, it's stored from the previous time that rendered all of your components. And if there are any differences in the output, react will update the DOM elements on the screen to match the new output from your components. It does not touch or change any of the DOM elements higher in the tree that it doesn't think have changed. This is the performance optimization.
It allows those elements on the screen to stay the same. You know, react doesn't have to run a bunch of extra code to, you know, delete them and re add them to the screen.
But how does react actually detect when something in the tree has changed? It has these two trees, right? But how does it actually detect when these trees are different from each other?
There is an algorithm in computer science that lets you detect differences between trees. If react use that algorithm, the performance optimizations would be completely transparent, and we wouldn't be talking about it now. So obviously, react doesn't use that algorithm, because that algorithm is too slow again.
So instead, react created their own algorithm that tries to guess, when the new output differs from the previous output, or when parts of the tree differ from each other without needing to sort of look in depth at the entire trees every time. This process is called reconciliation.
Ah, of course. Yeah. So Okay, let me try to Okay, okay. Okay. Well, that I'm not sure you can call my basic slug nervous system, a brain, but whatever you call, it is a chance to catch up here.
Okay, okay, of course.
Okay. So let me try to recap this. Rendering is the process react takes to run my component's code and figure out what changed from the previous run, so that it can update what is on the screen to match the latest output from my components. Reconciliation is a part of the rendering process where react actually figures out what changed, so it knows what to update on the screen. Did I get that correct?
Yes. If they don't call your nervous system of brain, they absolutely should, because you nailed it.
Thank you. Okay, so what is it about the performance optimizations then, that I actually do need to know about or care about?
Unfortunately, yes, you do need to care. And there are a few things. For the most part, it is transparent, but there are a few things you do need to be aware of.
So reconciliation is done by comparing the types of the nodes within the trees. So if the node in the same place in two trees are of the same type, like if the top node in both trees are dibs, then react knows it doesn't need to create a new DOM element and add it to the screen, it could reuse that div that's already on the screen, right? So it goes through both trees comparing the nodes in the same places in the trees. If it detects any type changes between the two, it destroys all the DOM elements on the screen from that point in the tree down and rebuilds them with the output from the new tree.
So if your component used to return a div, and now it returns a span, along with maybe some other React components, it's going to destroy and remove the original div and everything inside of it from the screen and rebuild it from the new tree.
So in technical terms, this is called a heuristic algorithm and is generally transparent to you as a programmer, you don't normally need to think about it except if you're specifically trying to optimize the performance of your program.
But there are Are there some special cases where you do need to be somewhat concerned about it, even if you're not doing performance optimizations, and a special case, where you do need to do some extra work to help out this heuristic algorithm is when you have a component that renders a list of other components or a list of other HTML DOM elements.
Like if you iterate over an array to build a list in your output, then you have to do something special. The first node in the output for the list needs to have the special property set called key. React takes the shortcut on lists and doesn't run its full hueristic algorithm. Instead, it only looks at the key property to determine if it needs to update the DOM element on the screen.
So whenever you render a list, you need to specify this key property and its value should be unique for the data in each list element, it should be stable, meaning it should always be the same value every time your component renders for that same list element.
I know this sounds like a lot, but react will remind you in the warnings if you ever forget the key property, and at least without getting into performance optimizations. That's pretty much it for rendering and reconciliation.
Okay, wow. So really, I don't need to care too much about how all of that works. I just need to make sure to specify the key property and list items. Is that correct?
Yes, exactly. In normal react programming, that is really the only extra thing you need to care about. Now, if you have performance issues, the knowing how that heuristic algorithm works is important because you can use it to your advantage to make your React programs faster. But I don't ever think or worry about it, except if I actually detect a performance issue.
Okay, so it sounds like in summary, if I'm getting this right, Thomas, react works by just running my component code whenever it thinks it needs to. And then by comparing the trees of output between renders, it can keep the internal state of my program in sync with what the user sees and interacts with on the screen.
Yes, that is an excellent summary. Now I need to figure out how your slugged nervous system works because you are one excellent student.
Well, I'm not sure it is compatible with your system, but maybe we can run a reconciliation algorithm on our nervous systems and see the difference sometime.
Okay, yeah, absolutely. How about you get your new React ticketing system web application working and we can use your new calendar component to schedule a time to do a nervous system reconciliation.
I can't wait. I wish maybe I can even sell tickets to that event.
Yeah, I would. I would love that Norris. I just want to thank you once again for joining us. I had a lot of fun talking through the mechanics of react in a super condensed and fast way and I hope it is helpful to you.
Yeah, absolutely. I feel like I understand react a lot better now. I think I will need to practice and read the documentation and look at some examples to fully get it but at least I now know how it all fits together.
Thank you for having me on the show. And if your listeners are ever down in the Baja California Sur area they are welcome to stop by my rock and I'll make them some roasted sponge or whatever they're into.
I'm not sure how much my listeners want to eat sponges. But I'll let them know. Thanks again Norris. It's been great. You have a good one.
All right, so that was the mechanics of React. I know it's definitely more beginner focus but I also know a lot of people listening to this are beginners maybe if you're not a beginner that was probably really boring and you didn't make it to this point but I hope it was at least still entertaining it was so Norris is is based on a really awesome slug that sea slug that we actually did find tide pooling down in Baja, Mexico.
Just it's it was actually a pretty common slug but it was just so different from anything that we normally see up in the United States and California it has a whole bunch of really cool colors and yeah like to be under rocks, at least during the day when the low tides were I assumed because the sun is really intense down there. So if you were careful and turned over a rock, you could find these slugs. There may be like, you know, one to two, maybe three millimeters in length. But yeah, it was really fun.
Yeah, so this this whole thing was based on on the Norris slug that that we saw quite a bit.
But yeah, if you're if you're into this whole mechanics of react and how it works and maybe you're not a beginner or maybe you're a beginner, but you really want to dive into things I've actually covered not not all of this, I really focused a lot more on some parts of it like rendering and reconciliation in a book that I wrote, called Foundations of high performance react, you can find it on the React's show.com. website.
So yeah, if you really want to get in depth in how this works, and, you know, get it in written form, and really dive in and learn not only the specific details of the heuristic algorithm and this entire process, but also learn how to optimize your React programs to take advantage of this algorithm.
Yeah, definitely check out the book. If you're able to purchase it, it really helps support the show. It makes it so we can continue to build and bring you awesome episodes like this. And you know, have Norris come visit and hang out with us. Right? Yeah.
And like I said before, if it's something you can't afford, just send me a message on the website. And I'll make sure to get you a copy some way. But either way. If you're interested, definitely check it out. Anyways, yeah, that's about all I have in the show for you today.
And I'm actually back in the San Francisco Bay area. I flew up from Mexico yesterday. I wrote this episode and worked on it down in Mexico just doing the recording today.
And yeah, a bit of I'll be honest, a bit of culture shock after spending a month in Mexico. It's like, why are the roads here absolutely gigantic. I won't complain about this. But definitely take it a bit of getting used to. And especially because even before that I I've been in the desert for like two months, two and a half months or something now straight. And in the Bay Area, I flew in and it was raining and everything is green. It's totally different. It's really cool. I haven't seen green and forever aside from a few like river deltas and stuff.
So yeah, it's fun, I'm looking forward to exploring some wildflowers and doing some other fun things.
And I've been Yeah, a little bit of inside information. I've been also working really hard on what I think is going to be this really fun series where me and a another person that we've worked with on the show before Jane, we're going to sort of compete with each other to create a, I'm not going to give away all the details yet. But we're going to create a program the same program together based on some specifications. But there's all sorts of fun things to make it more game like where you can choose maybe different paths and different features and different ways of doing things. You can choose to add tests or not add tests you can. And essentially, we're gonna play this game against each other to see who can create the best react version of this program. And score the most points and we have all sorts of fun things like you can throw, you know, you can attack the other player and they can defend or they can, you know, it'll be fun.
I am really looking forward to it. I don't feel like I super explained it all that well to make it all that enticing. But I could tell you, I think it's gonna be a lot of fun. And we've been working really hard on that. So it's gonna take a little bit to make and produce. But yeah, definitely stick around, subscribe, whatever, you know, you want to call if you're interested in that.
But yeah, I just want to say thank you once again for joining us and I hope you have a fantastic rest of your day. See ya. Bye