-1

Till now I thought the only reason child component is re-rendered is because of changing passed props. But I've created a CodeSandbox and it turns out that Child component which doesn't receive any props is re-rendered every time parent's state changes. So my question is: what are all reasons for re-rendering/updating Child component?

Here is App.js file:

import React from "react";
import ReactDOM from "react-dom";
import Child from "./Child";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      counter: 0
    };
  }

  componentDidMount() {
    console.log("Parent mounted");
  }

  componentDidUpdate() {
    console.log("Parent updated");
  }

  render() {
    return (
      <div>
        <button
          onClick={() =>
            this.setState(prevState => ({ counter: prevState.counter + 1 }))
          }
        >
          Increment
        </button>
        <button
          onClick={() =>
            this.setState(prevState => ({ counter: prevState.counter - 1 }))
          }
        >
          Decrement
        </button>
        <Child />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

And here is Child component:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class Child extends React.Component {
  componentDidMount() {
    console.log("Child mounted");
  }

  componentDidUpdate() {
    console.log("Child updated");
  }



  render() {
    return <div />;
  }
}

export default Child;

1 Answers1

0

There is difference between the 're-render' and the "update-process":

1.If a component re-render, then its child-component whill also begin the update process.

2.If the shouldComponentUpdate function of any component returns false, the update process is aborted.

When App changed its state, in fact, even App may not be re-rendered, if the shouldComponentUpdate return false, then App won't be-rendered, and the child component certainly won't.

Now, consume that the App start normal re-rendering, then as the child component, will definitely start the update process, but if Child's shouldComponentUpdate returns false, then the update process of Child will also be aborted and will not be re-rendered.

Alvin
  • 298
  • 2
  • 14