How React ACTUALLY works (DEEP DIVE 2023)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
for starters let's understand what react is and what it isn't react as a library yes not a framework only a library that lets you build user interfaces in its core it pretty much just lets you describe the UI you want to show by using components and it puts out a tree of elements that can be used to render the page react itself doesn't render the output in the browser for that you need to react to Dom which used to be part of react but as of right now is its own Library so react doesn't know what the output will be used for that's why you can take it and render it on mobile apps with react native for example or even create your own library that renders the output wherever you want react also keeps track of changes to data in your code and updates the output as soon as the data changes using something called State that's why it's called react it reacts to the changes and keeps the UI in sync let's take a look at the most basic way you can add react to a normal HTML page first we import react and react Dom by using script tags now we need to tell react where we we want to use it usually in a react project you send an empty HTML file to the client with only a div that is marked as the root and react inserts all the contents but that's not the only way you can use react anywhere you want let's create a div and give it an ID now let's create a simple like component it has a state of like and we set it to true if the user clicks on the button if liked is true we return a text string but if light is false which is the initial State we return a like button notice how I'm not writing any jsx which is the HTML like looking markup that you would usually see here this is because react actually doesn't understand jsx or HTML it's all just JavaScript so you need to describe what you want to render and pass it to the create element method in react as you can see in the first argument I tell it to create a button element in the second argument I give it an object with props in this case only one which is the on click prop and the third argument are children in this case it's just a string with the name of the button don't worry later we'll take a closer look now we need to tell react Dom where to insert this react component we create a root node by grabbing the div that we gave an ID earlier and tell it to render our alike component and finally let's import our like component using a script tag now as you can see we have our reactive like button and our normal HTML page when we click on it it changes the like state to True which triggers a re-render react noticed that the output is different and updates that part of the page to display the new state of the component now you understand what react does on a basic level but most people wouldn't want to use react like that in a normal project for a good developer experience you need to combine it with a set of other libraries that for example give you a live server so that you can see what you're building in real time including helpful errors and warnings you likely want to add Babel to be able to use jsx instead of describing the UI with JavaScript objects you want to have a bundler that bundles all your JavaScript code and so on that's why the react team created something called create react app that you're likely familiar with it gives you a ready out of the box react project with all these tools configured which makes setting up a react project a breeze this could in fact be called the framework however react itself is just a library and because of that you can put together your own tool chain or use something other than create react app some popular alternatives are parcel or my personal favorite Veet and then of course there is the really popular meta framework next.js now let's start diving deeper react as declarative instead of imperative which means you don't directly interact with the Dom like appending HTML elements or changing them you just describe the UI and react as the inserting and updating for you in the previous example we saw that react uses the create element method and expects a JavaScript object which describes the UI but that's not very practical especially if you're building a complex UI with lots of components luckily we have something called jsx which stands for JavaScript XML it lets you write HTML like syntax and this is what you're likely familiar with instead of creating this object we can just write it like this looks like normal HTML does image but if we now check our page the button is nowhere to be found that is because react doesn't understand jsx it expects an object not some weird HTML like markup so we need a step in between to convert it a library called Babel is used for that in our basic HTML page we can just add Babel using script tags and mark the like button component make sure to load Babble before the component now as you can see the like button works again and we can use jsx so we learned that jsx is cool because you can write HTML like syntax but what does html like even mean jsx and HTML are actually not the same first of all jsx is more strict for example it doesn't allows Health closing tags like image you have to close them also you have to always return exactly one root element you can't return multiple if you want to do that you have to either wrap it with for example a div or you can use a react fragment which will be ignored and not appear in the done and the last thing that makes jsx really powerful is that you can break guard of the HTML syntax and insert JavaScript wherever you want this is really powerful because you can express your UI however you want and you don't need to learn any new syntax like an angular or view if you know JavaScript you can build uis as complex as you want right away but there is a downside to it even you the creator of vue.js held a really great presentation in which he mentioned this I highly recommend you watch it he explains that this approach leads to countless different ways the UI can be constructed and changed so when react needs to re-render your components it gets hard to predict what changed and where because anything is possible it's hard to make assumptions which causes more work and makes this process slower however if you have a template based syntax like view or angular you're more restricted on the other hand View and angular can make more assumptions because they know what can and what can't change in your component which leads to better performance as you can see jsx freedom of expression is a double-edged sword now let's take a look at how react knows when to update the UI and how that process actually works there are three steps to this trigger render and commit the first step is the trigger there are two cases which kick off the render process the first time the component is rendered which happens in create root and then every time one or more states are updated in the component or in a component that is higher up in the tree its ancestor let's see that in action if we put in a console log here it will be executed on every render if we refresh the page we can see react rendered this component once if we now click on the button that changes the state of like from false to true we can see the trigger is a re-render of the component now what if the like button component is inside a different component if a state and the component above changes does it affect it in this example we have a card component with a title that comes from a state and changes when we click on this button I also put in a console login here now if I click on this button type that the title as you can see it also causes a re-render of the light component which is nested inside of it also notice how I set one or more State changes I'll show you what I mean let's take a look at this example here we have two states that are updated at the same time on click if we click on this button we can see that the component was not rendered two times but once this is because react doesn't immediately start the rendering process it batches State updates to avoid too many re-renders this can be a bit unintuitive at first and be a common cause for a box so here's a bonus tip let's counterlock the state value after we update the state notice how the value is not the one that we set before the console log the reason for that is that the changes don't take place immediately the update of the value happens after the code is executed and it's safe to update the state which creates a delay let's take a look at this example we have a button that increases the count by one three times in a row but if we click on it it only increases the count by one why is that when a render is triggered react creates something like a snapshot of this component and it's state that means the same snapshot is used in all of these three lines and the state count is zero every time when the code is executed we're adding one but basically resetting it again in the next line because we're using the alt zero value from the snapshot and adding one to it so the end result is one if we want to make sure that the previous state and the queue is passed instead of giving the setter function only a value we can pass it a function that has the most recent State add one to that and return it see now it works now let's go back and continue with the rendering process okay after the trigger react calls the component in which the trigger appeared that means it just calls the functions because components are just functions that return a react element and this process is recursive that means if the component contains other nested components it will call them as well until it reaches the end and nothing is left to call what we end up with is a lightweight representation of what the UI should look like as a tree of react elements which is called to the virtual Dom since react already created one in the beginning it now has two an old one and a new one then a different algorithm Compares these two trees and figures out what has changed and the last tab react modifies the Dom to reflect the changes using the least amount of necessary operations and it only touches the Dom nodes that actually have changed technically there is actually a fourth step which is your browser that now has to repaint to reflect the changes that's the overview of the whole process but of course there is a lot happening and I skipped over some important details let's take a closer look after hearing all of this you may ask yourself why is this whole process needed why not just skip over the whole virtual Dom part the answer is performance creating a few hundred or thousands of JavaScript objects is way faster and cheaper than writing directly to the Dom that's one of the most expensive things that you can do so if you have a complex UI performance will take a hit if every time something changes you directly modify the Dom that's where I react creates this lightweight representation of the Dom using a tree of JavaScript objects bundles all the changes and commits them to the Dom in one go but figuring out the differences between trees is actually really difficult even with state-of-the-art algorithms the complexity of calculating the differences is an order of Big O of n cubed where n is the number of elements in the tree if we have a tree with thousand elements it would require roughly 1 billion comparisons because that is way too expensive in order to reduce the number of comparisons react makes two assumptions first different element types produce different trees and second Keys stay consistent across re-renders let's check out both of these statements react stiffing algorithm compares the old and the new trees side by side line by line and as soon as it finds a change in the element type it assumes that the UI will look different from there on even if the component is high up in the tree it will rebuild everything that is nested inside of it now let's take a look what keys are and what role they play for the different algorithm you might know that you can give keys to react Elements by default it's null but you can pass it a value which is often used when rendering lists for example first let's take a look what happens if you don't do that here we have an array of items and we use the map method to generate a list item for each of them what happens if we append a list item reactor will go line by line compare them see that all of these items stay the same and at the end notice that an item has been added so there is only one difference here and all react has to do is append this and the Dom but what if you pre-pant a list item now react compares the first item of the old tree with a newly added item in the new tree and sees it's different the second list item is different too because everything is shifted by one it will have to tear down everything and create the list from scratch even though that's not really efficient by providing keys that should stay the same across renders we can help react understand which items State and don't need to be rebuilt ideally you want to use something like an item ID that always stays the same a common mistake is to use index as a key in the first case it would work but in the second case like here you can see that the index doesn't stay the same because everything is shifted by one so the first item in the alt list has a different indexed in the new tree that's not helpful Another Thing Worth pointing out is that state is the only thing that persists across Runners if you declare normal variables without using State they will be resetted on each render also changing them doesn't cause a re-render they should only be used to store data that doesn't change or for computed values such as a full name that is constructed from my first and last name for example now you should have a good idea of what is happening under the hood and I hope this will help you in your next react project you might have noticed that I didn't go deep into some topics such as state use effect other hooks react fiber and so on if you want to see a part 2 let me know and I'll cover that as well anyway that's it for this one I'll see you in the next one
Info
Channel: FrontStart
Views: 52,654
Rating: undefined out of 5
Keywords: React, Learn React, How react works, React tutorial, How does react work, React advanced, React for beginners, React for advanced, React deep dive, Learn React 2023, React 2023, Javascript framework 2023, Frontend frameworks 2023, React state, Create react app, Create react app 2023, Create react app project, React vite, React with vite, React parcel, React Nextjs, React Nextjs 13, React Nextjs 13 tutorial, React interview, React how to, Learn frontend framework
Id: za2FZ8QCE18
Channel Id: undefined
Length: 12min 59sec (779 seconds)
Published: Fri May 19 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.