Search code examples
reactjsvirtual-dom

virtual-dom and shouldComponentUpdate


If I was right, the Virtual DOM in ReactJS compares the previous DOM with the current DOM i.e, formed after a change in state tree. Then why the child components rerenders when there is change in parent props.

If virtual DOM renders only the DOM that is not already rendered, why should I use shouldComponentUpdate() method.

I have watched many videos on this but I didn't get exact way they behave. It would be a great pleasure if someone can clearly explain the following doubts.

1) Does virtual DOM every-time renders only the components which are not already rendered or will there be any exceptions?

2)If virtual DOM every-time renders only the components which are not already rendered, why the child components re-renders when there is change in parent props?

3)When should I use shouldComponentUpdate()?


Solution

  • 1) Does virtual DOM every-time renders only the components which are not already rendered or will there be any exceptions?

    The Virtual DOM is an abstraction of the HTML DOM. Since the DOM itself was already an abstraction, the virtual DOM is, in fact, an abstraction of an abstraction. What virtual DOM does is that instead of rendering the whole page, it renders only the components with the changes. There can be all the components already present but if a change has occurred in one component it only re-renders that component.

    2) If virtual DOM every-time renders only the components which are not already rendered, why the child components re-renders when there is change in parent props?

    The child components re-render when there is a change in parent props is because the props are passed to child components and they behave according to those props. And as mentioned above, whenever there is a change, the component re-renders.

    3) When should I use shouldComponentUpdate()?

    shouldComponentUpdate() is used to optimize re-renders. The method either returns true or false. It is up to you that how you want your component to render and re-render. It is basically used for performance enhancement. There might be cases when you don't want the component to re-render even on state change, so you use this method. For example:

    shouldComponentUpdate(nextProps, nextState) {
      if(this.props.abc !== nextProps.abc) {
        // anything you want to do and return true or false accordingly
      }
    }