Ever wonder how React takes your code and creates what you see on the screen? Or how React knows whether to update your component or not?
Learning how rendering works in React will allow you to optimize your apps and make better decisions on how to structure your React application.
Let's get started...
There are two phases to the React rendering cycle.
The render phase and the commit phase.
There are also two types of renders. An initial render and a re-render. Initial rendering is when your app first starts up. A re-render is when your state or props have updated.
Once the Virtual DOM is created, React will compare what it has built out to what the actual DOM has using a fancy diff algorithm. However, once it has finished comparing it ends up with a list of what needs to be changed. This is still considered part of the rendering phase.
Side Note: It's important to note that React goes through its virtualDOM and creates a list of those changes that need to be made to the actual DOM. Meaning that React will wait to commit all the updates so it does it in one swift process and not in parts. This is what it means when you read that React does batch updates. This is crucial to understand when working with state.
Re-rendering is similar, but with one key difference. It does not go through every component to check for updates. Instead, when your component state or props update React uses a flag to mark that component. Basically saying that this component has been marked for an update.
Once React has done the comparison between its new and old components using that diff algorithm and has a list of changes. It will go ahead and surgically apply those changes to the actual DOM. Meaning that it will only change the particular elements of the DOM that have changes, not every single element. This is called the commit phase.
The commit phase is where React actually touches the DOM and makes changes.
It's important to point out that React may go through the render phase but never commit. This can happen if the component returns the same result as the last time. Often happening if the parent component's state updates causing a render, but the child component(s) still create the same output anyways.