Home > Blockchain >  Why use React.memo() if React already uses Virtual DOM concept?
Why use React.memo() if React already uses Virtual DOM concept?

Time:01-17

I am beginner in React JS. I came across React.memo() a HOC component that basically only re-renders the component if the component execution results are different from its previous result which it memonizes. But why do we need to use it if there is already a concept of Virtual DOM? Like doesn't the Virtual DOM concept also do the same thing that is not re-rendering the component if the resultant virtual DOM is the same as the main DOM? If I get it correctly aren't both follow same concept functionality wise?

CodePudding user response:

React rendering happens at multiple levels. The virtual DOM kicks in at React<->Browser, but using React.memo() can reduce the amount of times that your React code needs to be run. In short:

Virtual DOM: Reduces HTML element creation/edits

React.memo(): Reduce React component re-renders (before even touching HTML)

CodePudding user response:

For it's own - yes, similar to Virtual DOM. But from documentation:

[The memo()] component will usually not be re-rendered when its parent component is re-rendered. […] memoization is only a performance optimization. […] React normally re-renders a component whenever its parent re-renders.

So in other words you can use React.memo() to optimize component if you know that even if parent has changed, this component will not change.

CodePudding user response:

React will execute your function component, compare it to the dom and will update if there are changes. If you use React.memo() your function component will not be executed again and it won't be compared to the dom.

So if you have a calculation in your function compoent that takes one second, without React.memo() it will run this calculation again.

  • Related