Dimitris Karagiannis
Dimitris Karagiannis

Reputation: 9376

Following the initial ReactDOM.render is the whole DOM ready when the componentDidMount methods start firing?

Consider the following code:

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

class CompA extends React.Component {
  componentDidMount() {
    console.log("a");
    debugger;
  }
  render() {
    return <div>Component A</div>;
  }
}

class CompB extends React.Component {
  componentDidMount() {
    console.log("b");
  }
  render() {
    return <div>Component B</div>;
  }
}

class CompC extends React.Component {
  componentDidMount() {
    console.log("c");
  }
  render() {
    return <div>Component C</div>;
  }
}

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

  render() {
    return (
      <div id="top-level-component">
        <h1>Hello!</h1>
        <CompA />
        <CompB />
        <CompC />
      </div>
    );
  }
}

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

Link to Codesanbox

I have three questions:

Question 1

In the initial render from ReactDOM.render(), only a single append operation happens (i.e. the #top-level-component DOM element, which already contains all of its children, is appended to the #root DOM element), instead of appending #top-level-component to the #root, and then appending its children's DOM elements to the #top-level-componentDOM element. Correct?

Question 2

The componentDidMount methods of the components fire after that single append operation has happened, bottom to top, in order, meaning the console will log

a
b
c
App

This means that when the componentDidMount of CompA fires, the whole DOM is ready and if it's necessary, it can possibly query the DOM for one of its siblings. Correct?

Question 3

Following the above, is it generally safe (meaning in component mountings that happen later, after the initial ReactDOM.render()) to assume that when we have some sibling components, when the first sibling's componentDidMount fires the other siblings' DOM representations are already flushed into the DOM?

Upvotes: 2

Views: 304

Answers (1)

Chris
Chris

Reputation: 59531

Q1: Correct. React will only append to the DOM once it has the full virtual-DOM calculated and ready to be inserted. This is the absolute final stage of the rendering process.

Q2: Correct.

Q3: If I understood your question correctly, yes. Again, like in question 1, DOM flushing only happens ONCE during any one render.

I suggest you take a look at the Reconciliation part of the official documentation for more info about how React builds the virtual-DOM.

Also, if you want to play around with ReactDOM.render(), you could do:

const func = () => {
  console.log("ReactDOM.render() fired!");
  return <App />;
}

ReactDOM.render(func(), document.getElementById("root"));

to see when and how many times it fires.

Upvotes: 3

Related Questions