This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021
useEffect
By default, useEffect executes asynchronously at the end of each rendering round. Unlike Class Component componentDidUpdate and componentDidMount, which execute synchronously after rendering, useEffect does not block browser rendering.
useLayoutEffect
UseLayoutEffect works almost as well as useEffect, except that useLayoutEffect is executed synchronously, just like componentDidUpdate and componentDidMount. These changes are executed immediately before the browser renders them.
Usage scenarios
UseEffect is used almost 99% of the time on the project.
The scene of a
- If the component has a flash during a state update: the initial state value is displayed, and then the updated value is displayed, with a very short interval between changes, the interaction will look like a flash
useEffect
Replace withuseLayoutEffect
. - And that’s because,
useLayoutEffect
Is to execute its callback function (which blocks page rendering) synchronously before the update is ready to complete, whileuseLayoutEffect
There are also internal operations that trigger component updates, so the initial state is virtualDOM
The value of is updated twice before it is updated to trueDOM
, and finally shows only one updateDOM
The effect is to reduce the consumption of backflow or redrawing of the real DOM, so there is no flicker. The following code:
import React, {
useState,
useLayoutEffect
} from 'react';
import ReactDOM from 'react-dom';
const BlinkyRender = () = > {
const [value, setValue] = useState(0);
useLayoutEffect(() = > {
if (value === 0) {
setValue(10 + Math.random() * 200);
}
}, [value]);
return (
<div onClick={()= > setValue(0)}>
value: {value}
</div>
);
};
ReactDOM.render(
<BlinkyRender />.document.querySelector('#root'));Copy the code
Scenario 2
Before any other code runs that might update a variable (such as ref), if you want to access the current value of the variable, use useLayoutEffect, as in the following example:
const ref = React.useRef()
React.useEffect(() = > {
ref.current = 'new value' // The code that affects ref updates
})
React.useLayoutEffect(() = > {
console.log(ref.current) // Get the value before update instead of "new value"
})
Copy the code
conclusion
- Most of the
99%
The case is non-blocking using asynchronous executionuseEffect
, the user can see it fasterDOM
update - It is not recommended for use except in special cases
useLayoutEffect
useLayoutEffect
The execution time of theDOM
The update is executed before the browser completes rendering (drawing)
reference
useEffect vs useLayoutEffect
When to useLayoutEffect Instead of useEffect