useEffect

The react rendering component executes after the callback, and the process of ensuring that the callback does not prevent the browser from drawing (asynchronously) looks like this:

  1. Triggers an action that causes a re-render (changing state, props)
  2. React rerender component (call)
  3. You can see the update on the screen
  4. UseEffect callback execution

useLayoutEffect

After the React rendering component is executed synchronously, the execution process looks like this:

  1. Triggers an action that causes a re-render (changing state, props)
  2. React rerender component (call)
  3. The useLayoutEffect callback function is executed
  4. Screen see update

Code sample

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

const BlinkyRender = () => {
  const [value, setValue] = useState(0);

  useEffect(() => {
    if (value === 0) {
      setValue(10 + Math.random() * 200);
    }
  }, [value]);

  console.log("render", value);

  return (
    <div onClick={() => setValue(0)}>value: {value}</div>
  );
};

ReactDOM.render(
  <BlinkyRender />,
  document.querySelector("#root")
);
Copy the code

< div style = “color: RGB (0, 0, 0); font-size: 10px! Important;”

  1. Click on the div
  2. State changed, causing the React component to reexecute
  3. Update the screen
  4. UseEffect execution, state changes again
  5. The React component reexecutes and the screen is updated

UseLayoutEffect execution process:

  1. Click on the div
  2. The React component executes again when state changes
  3. UseLayoutEffect, state changed
  4. The React component performs the update again
  5. Update the screen

conclusion

  • UseLayoutEffect is synchronous, and the browser will not update until the callback is executed. If the callback takes too long, the image will not be updated. In most cases, useEffect is used
  • If the screen flickers, please try useLayoutEffect

Reference article: daveceddia.com/useeffect-v…