DOM Manipulation in React


This React series will cover everything and will take you from beginner to intermediate in React and JavaScript. Latest post regarding DOM Manipulation let's know the process...


DOM Manipulation

DOM Manipulation is the process by which one can dynamically change the content of the web page. Working with DOM should be fairly easy and quick as it is always tree-structured, traversing the DOM is easy.

In React, changes are made to the Virtual DOM and then synced to the React DOM. This process is call Reconciliation. React can figure out which objects have been changed, and this process is called drifting.


Process of DOM manipulation

  • React will update the Virtual DOM
  • The previous state virtual DOM will then be compared with the updated Virtual DOM, to identify what has been changed in the objects. This is done using the Diffing Algorithm.
  • The changed objects will get updated on the Real DOM.

Example of Diffing Algorithm

  • When the root element is different

    // Old version
    <div><Tree/></div>
    // New update
    <span><Tree/></span>
    

    React will delete the tree, and rebuild the entire tree again.

  • When the Attribute is changed in the element

    // Old
    <span id="span1" />
    //New
    <span id="span2" />
    

    Only the difference will be found in the attribute and will be changed accordingly.

  • New child element added at the end

    // old
    <ul>
        <li>Child1</li>
        <li>Child2</li>
    </ul>
    //New
    <ul>
        <li>Child1</li>
        <li>Child2</li>
        <li>Child3</li>
    </ul>
    

    The new element will be added to the end of the list.

  • New element added at the beginning of the list

    // Old 
    <ul>
        <li>Child1</li>
        <li>Child2</li>
    </ul>
    //New
    <ul>
        <li>Child3</li>
        <li>Child1</li>
        <li>Child2</li>
    </ul>
    

As the new element is added to the beginning it will be rebuilding the entire list again.


☕Thanks For Reading | Happy Coding🤨

No Comments Yet