lundi 19 avril 2021

How does the React render actually translate to Browser painting elements on screen?

I have created a small React example where I am simulating a state change every 1s.

I have enabled Show paint flashing rectangles from Chrome developer tools to examine the UI.

After each second, I am getting a new paint signified by the greenish color.

Following is the code for React App without memo :-

import "./App.css";
import React, { useEffect, useState } from "react";

function App() {
  const [_, setState] = useState(0);
  useEffect(() => {
    setInterval(() => {
      setState((state) => state + 1);
    }, 1000);
  }, []);
  return <DIV />;
}

const DIV = () => {
  console.log("render");
  return <div className="App">Text</div>;
};

export default App;

Following is the React.memo variation :-

import "./App.css";
import React, { useEffect, useState } from "react";

function App() {
  const [_, setState] = useState(0);
  useEffect(() => {
    setInterval(() => {
      setState((state) => state + 1);
    }, 1000);
  }, []);
  return <DIV />;
}

const DIV = React.memo(() => {
  console.log("render");
  return <div className="App">Text</div>;
});

export default App;

App CSS :-

.App {
  text-align: center;
  height: 200px;
  background: black;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

In both of the above cases, the paint flashing occurs on the UI.

  • In first scenario, why does each render cause the black div to be painted again ?
  • In second scenario, there is no render due to React.memo but still black div is painted again ?

How does the React render actually translate to Browser painting elements on screen ?

Below is the gif for it :-

Painting




Aucun commentaire:

Enregistrer un commentaire