DEV Community

Leandro Roggerone
Leandro Roggerone

Posted on

component process order

Hello , guys ... Im react beginner trying to understand rendering orden on nested components .. lets supose following structure and console output.

import { useState, useEffect } from 'react'
import React from 'react'

export const Comp2 = () => {
  console.log("from component 2")
  useEffect(() => {
    console.log("from component 2 useEffect")
  })

  return (
    <>
    <div>Component 2</div>
    <Comp3/>
    </>
  )
}
export const Comp1 = () => {
  console.log("from component 1");
  useEffect(() => {
    console.log("from component 1 useEffect")
  })


  return (
    <>
    <div>Component 1</div>
    <Comp2/>
    </>
  )
}
export const Comp3 = () => {
  const [count3 , setCount3] = useState(10)
  console.log("from component 3");
  useEffect(() => {
      console.log("from component 3 useEffect")
    })

  return (
      <>
      <div>Comp3</div>
      <button onClick={()=>{setCount3((count) => count + 1)}} >increment counter3</button>
      <span>{count3}</span>
      </>
    )
}

function App() {
  const [count1, setCount1] = useState(0)
  const [count2, setCount2] = useState(0)

  console.log("Starting  count1 / count2:", count1,count2);

  useEffect(() => {
    console.log("from App useEffect")
  }, )

  return (
    <>
      <button onClick={()=>{setCount1((count) => count + 1)}} >incrementar contador 1</button>
      <span>{count1}</span>
      <button onClick={()=>{setCount2((count) => count + 1)}} >incrementar contador 2</button>
      <span>{count2}</span>
      <Comp1/>
    </>
  )

}

export default App
Enter fullscreen mode Exit fullscreen mode

After F5 on browser, Im recibing following output:

Starting  count1 / count2: 0 0
from component 1
from component 2
from component 3
from component 3 useEffect
from component 2 useEffect
from component 1 useEffect
from App useEffect
Enter fullscreen mode Exit fullscreen mode

I have following thoughts:
1 Components Processing order depends on nesting order.
2 Why log lines are printed in order begging on the father component to deeper child ?
3 Why log lines inside useEffect hooks are printed on reverse order?
4 Incrementing counter 3 only triggers component 3 render...
5 Incrementing counter 1 or 2 renders all nested components,How can I prevent this?

Any brief explaination / document to read would be great.
thanks.

Top comments (0)