Home > Software engineering >  Why theses two divs doesn't render the same way?
Why theses two divs doesn't render the same way?

Time:08-08

When I run this, it doesn't render the same way although it is the same from my beginner pov. For example, I can't expand the first one div in the console dev tools, but I can expand the second one !

Link, I haven't the right to post images

Why ?

import React from "react"

export default function App() {

    const [time, setTime] = React.useState(0)

    React.useEffect(() => {
        const lol = setTimeout(() => setTime(prev => prev   1), 100)
        return () => clearTimeout(lol)
    }
        , [time]
    )

    function ComponentTimer() {
        return <div> (I can't open this div in the console) Time : {time / 10} sec</div>
    }

    return (
        <main>
            {<ComponentTimer />}
            <div> (but I can open this one) Time : {time / 10} sec</div>
        </main>
    )
}

CodePudding user response:

In the first It is a component and you are changing state after 100ms which will re-render the whole component. If you want to see both exactly like same all you have to do is extract ComponentTimer outside and pass time as a props as:

STACKBLITZ DEMO

function ComponentTimer({ time }) {
  return (
    <div> (I can't open this div in the console) Time : {time / 10} sec</div>
  );
}
export default function App() {
  const [time, setTime] = React.useState(0);

  React.useEffect(() => {
    const lol = setTimeout(() => setTime((prev) => prev   1), 100);
    return () => clearTimeout(lol);
  }, [time]);

  return (
    <main>
      <ComponentTimer time={time} />
      <div> (but I can open this one) Time : {time / 10} sec</div>
    </main>
  );
}
  • Related