Home   reactjs  

how component is rendered when the state is changed in react

In React, setState is a crucial function used to update a component's state. When setState is called, React automatically triggers a re-render of the component. Here's a detailed explanation of how this process works:

How setState Triggers a Re-Render

  1. Initial State:

    • When a React component is first created, it has an initial state defined, usually in the constructor or as a class field.
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          count: 0
        };
      }
    }
    
  2. State Update with setState:

    • When the component's state needs to be updated, setState is called with the new state values.
    incrementCount = () => {
      this.setState({ count: this.state.count + 1 });
    }
    
  3. Scheduling an Update:

    • setState is asynchronous. When it is called, React schedules an update to the component's state and marks the component for re-rendering.
    • React batches multiple state updates to improve performance.
    this.setState({ count: this.state.count + 1 });
    this.setState({ count: this.state.count + 2 });
    // Only one re-render is triggered with count being incremented by 2.
    
  4. Component Re-Render:

    • React re-renders the component by calling the render method. The new state is passed to the component, and the component is re-rendered with the updated state.
    render() {
      return (
        <div>
          <p>Count: {this.state.count}</p>
          <button onClick={this.incrementCount}>Increment</button>
        </div>
      );
    }
    
  5. Virtual DOM Diffing:

    • React compares the new virtual DOM with the previous virtual DOM to determine what has changed.
    • This process is called "reconciliation."
    • Only the parts of the DOM that have changed are updated, making the update process efficient.
  6. Updating the Real DOM:

    • Based on the differences found during the reconciliation process, React updates the real DOM.
    • This ensures minimal updates to the DOM, which improves performance.

Example

Here's a complete example to illustrate this process:

import React from 'react';

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    console.log('Rendering...');
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

export default Counter;
Published on: Jul 04, 2024, 12:59 PM  
 

Comments

Add your comment