So, how does the react update real DOM i.e. in the browser?
render() method which is being called(in class-based components) doesn't update the content to real DOM and neither the JSX in the return statement of functional components. The name here can be misleading
render doesn't mean that it should render, but think of it as a suggestion for how the final result will look like. Let's look at two important cases
- There are no changes in some parts of the final web page but the
rendermethod is being called, which is unnecessary in this case.
- Some props may change but we don't want to show it on our webpage. so
renderwill be unnecessary again.
In such cases, we might use
shouldComponentUpdate() in class-based components or
React.memo in the function-based component, but what happens when we do not use these, will it rerender every time if there are changes in props which are not used for UI or if the parent component renders it? NO It will not.
So, when the render is called/suggested it compares virtual DOM's. It will have Old Virtual DOM and re-rendered Virtual DOM. React takes this approach because it's faster. Here re-rendered virtual DOM will be created when the render method is called.
Once the comparison is made and if any differences are found then React will update the real DOM and note that it doesn't rerender the entire DOM. Suppose, the text on the button is changed then it won't rerender the whole button instead only text is changed. And it doesn't touch is real DOM if there aren't any differences.
This technique is awesome, isn't it? As you know accessing the real DOM is expensive (Why is it?) and this is something you wanna do as little as possible. As react has this virtual DOM idea the real DOM is touched only if it's necessary.
Hope you enjoyed this post,