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:
- Triggers an action that causes a re-render (changing state, props)
- React rerender component (call)
- You can see the update on the screen
- UseEffect callback execution
useLayoutEffect
After the React rendering component is executed synchronously, the execution process looks like this:
- Triggers an action that causes a re-render (changing state, props)
- React rerender component (call)
- The useLayoutEffect callback function is executed
- 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;”
- Click on the div
- State changed, causing the React component to reexecute
- Update the screen
- UseEffect execution, state changes again
- The React component reexecutes and the screen is updated
UseLayoutEffect execution process:
- Click on the div
- The React component executes again when state changes
- UseLayoutEffect, state changed
- The React component performs the update again
- 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…