Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React lifecycle methods. When does an app render to the screen?

I've read numerous articles on React's lifecycle methods and I can't seem to get an answer to a question I'm struggling with.

I have a relatively simple app that I've written that renders:

ReactDOM.render(<Root />, document.getElementById('Root'))

Root looks like:

<ApolloProvider client={client}>
  <BrowserRouter>
    <App />
  </BrowserRouter>
</ApolloProvider>

App has a few components inside it.

I have placed console.logs within each components componentDidMount methods and the order they log is as follows:

  1. Component 1 (child to 2)
  2. Component 2 (child to APP)
  3. App (child to BrowserRouter)
  4. BrowserRouter (child to ApolloProvider)
  5. ApolloProvider (Child to Root)

My question is, once Component 2 for example has rendered and componentDidMount executed, does that mean the component is visible on the screen or do all the components have to mount first to the virtual DOM, before the actual browser DOM is updated?

When does a React app actually update the browser DOM?

like image 780
Cazineer Avatar asked Aug 22 '26 19:08

Cazineer


1 Answers

After some reading and research, I think the following example might give you some light:

Imagine I have 3 Components: A, B, C, such that:

<A>
 <B>
  <C/>
 </B>
</A>

Now, the order in which the rendering, DOM updation(painting) and life cycle Did methods get executed are:

A.render() -> B.render() -> C.render() -> Reconciliation and DOM update -> C.componentDidMount() -> B.componentDidMount() -> A.componentDidMount()

render() function returns a new element, and this is input to the reconciliation process, which is responsible for DOM updating. If the component has children, the childrens' render methods are called, and only after the last child in the tree does the browser painting happens.

My question is, once Component 2 for example has rendered and componentDidMount executed, does that mean the component is visible on the screen or ....

Yes, I'd like to think so. componentDidMount and componentDidUpdate are called only after the actual DOM updation has taken place, always.

Also see https://medium.com/@gethylgeorge/how-virtual-dom-and-diffing-works-in-react-6fc805f9f84e, which looks like an in-depth explanation of how updation in React works.

like image 112
Dane Avatar answered Aug 24 '26 08:08

Dane