How to know when the virtual DOM and real DOM update happens?

Asked

Viewed 298 times

0

I’m developing a project in React and noticed that using multiple setState() followed caused the surrender of my component again, for example:

function MeuComponente() {
  console.log("Componente renderizado ");

  const [stateA, setStateA] = React.useState(false);
  const [stateB, setStateB] = React.useState(false);

  // useEffect apenas para atualizar o state uma única vez, não em todo render
  React.useEffect(() => {
    setTimeout(() => {
      console.log("Atualizando state");
      setStateA(true);
      setStateB(true);
    }, 1000);
  }, []);

  return <div ></div>
}

ReactDOM.render(<MeuComponente />, document.querySelector('#app'));
<div id="app"></div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

It worried me a little bit because I thought React made one batch ("lot") of setState to render only once. I searched and found in Soen a reply for this. Highlighting the main point:

Rendering (in the React context) and confirming virtual DOM updates in the real DOM are different issues. (...) React can do one batch of calls setState and update the DOM of the browser with the new final state.

Starting from the point that this is really right, I was left with these doubts:

  1. How do I know when the virtual DOM update happens? I imagine it is with each component return, but I’m not sure.
  2. How to know when the real DOM update happens?
  • Your question is in the sense of learning and understanding the virtual DOM mechanisms or do you have code you want to run when the DOM is changed?

  • Learning. The most I’ll do is use this to detect components that are being updated excessively in the DOM. For example, by placing a console.log update, but does not need to be a solution via code, can be through an extension also type React Developer Tools

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.