Virtual DOM in React

  • By Sonal Vanarse 
  • October 15, 2024
  • JavaScript
Virtual DOM in React

Virtual DOM in React

The Virtual DOM in React is a lightweight, in-memory representation of the actual DOM. React uses this abstraction to efficiently update the UI without directly manipulating the browser’s DOM, which can be slow and resource-intensive.

 

How the Virtual DOM works:

  1. Initial Rendering: When a React component renders for the first time, a virtual DOM tree is created based on the component’s structure.
  2. Updating: When a component’s state or props change, a new virtual DOM tree is created to represent the updated state.
  3. Diffing Algorithm (Reconciliation): React compares the new virtual DOM tree with the previous one using a process called “reconciliation.” It calculates the minimum number of changes needed (the “diff”).
  4. Batching and Efficient Updates: React updates only the parts of the actual DOM that have changed, reducing the number of manipulations and improving performance.

 

Class Component Lifecycle:

In React class components, the lifecycle is a series of events or methods that are triggered at different stages of a component’s life. These stages include mounting, updating, and unmounting.

1. Mounting Phase:

  • Constructor():
    • Called when a component is created.
    • Used for initializing state and binding event handlers.
    • Example:

jsx

Copy code

constructor(props) {

    super(props);

    this.state = { counter: 0 };

}

  • static getDerivedStateFromProps():
    • Called before rendering. Used to update the state in response to prop changes.
    • Returns an updated state or null.
    • Example:

jsx

Copy code

static getDerivedStateFromProps(props, state) {

    if (props.newValue !== state.currentValue) {

        return { currentValue: props.newValue };

    }

    return null;

}

  • render():
    • The only required method in a class component.
    • Returns JSX that defines the UI of the component.
    • Example:

jsx

Copy code

render() {

    return <div>{this.state.counter}</div>;

}

  • componentDidMount():
    • Called after the component is rendered into the DOM for the first time.
    • Commonly used for side effects like fetching data or interacting with the DOM.
    • Example:

jsx

Copy code

componentDidMount() {

    fetch(‘/api/data’).then(response => response.json()).then(data => this.setState({ data }));

}

 

2. Updating Phase:

  • static getDerivedStateFromProps():
    • This is also called during updates if the component’s props change.
  • shouldComponentUpdate():
    • Determines if the component should re-render. By default, it returns true.
    • Useful for performance optimization.
    • Example:

jsx

Copy code

shouldComponentUpdate(nextProps, nextState) {

    return nextProps.value !== this.props.value;

}

  • render():
    • Called during every update, re-rendering the UI based on the new state or props.
  • getSnapshotBeforeUpdate():
    • Called before the actual DOM updates.
    • Can capture the current position or other DOM-related values before changes are made.
    • Example:

jsx

Copy code

getSnapshotBeforeUpdate(prevProps, prevState) {

    if (prevProps.list.length < this.props.list.length) {

        return this.listRef.scrollHeight;

    }

    return null;

}

  • componentDidUpdate():
    • Called after the component has been updated in the DOM.
    • Useful for interacting with the DOM or making asynchronous calls based on the previous state.
    • Example:

jsx

Copy code

componentDidUpdate(prevProps, prevState, snapshot) {

    if (snapshot !== null) {

        this.listRef.scrollTop += snapshot;

    }

}

3. Unmounting Phase:

  • componentWillUnmount():
    • Called just before the component is removed from the DOM.
    • Useful for cleaning up resources (e.g., cancelling network requests, clearing timers).
    • Example:

jsx

Copy code

componentWillUnmount() {

    clearInterval(this.intervalID);

}

 

For Free Demo classes Call: 8237077325

Registration Link: React JS Classes in Pune!

 

4. Error Handling Phase:

  • componentDidCatch():
    • Called when an error occurs during rendering, in lifecycle methods, or in constructors of child components.
    • Example:

jsx

Copy code

componentDidCatch(error, info) {

    logErrorToService(error, info);

}

 

Lifecycle Flow Summary:

  1. Mounting: constructor() -> getDerivedStateFromProps() -> render() -> componentDidMount()
  2. Updating: getDerivedStateFromProps() -> shouldComponentUpdate() -> render() -> getSnapshotBeforeUpdate() -> componentDidUpdate()
  3. Unmounting: componentWillUnmount()
  4. Error Handling: componentDidCatch()

 

 Must watch our video on Demand For Full Stack Developers in Future

 

Author:-

Sonal Vanarse 

Call the Trainer and Book your free demo Class for ReactJS Call now!!!
| SevenMentor Pvt Ltd.

© Copyright 2021 | SevenMentor Pvt Ltd.

 

Submit Comment

Your email address will not be published. Required fields are marked *

*
*