UseEffect replaces componentDidMount and componentDidUpdate in React hook. The main function is to perform some side effects (such as DOM access, request data) when the page is rendered.
UseLayoutEffect works almost as well as useEffect. If you replace all the useEffect in your existing code with useLayoutEffect, you will hardly see any difference.
So what’s the difference? Look at the following code:
function App() {
const [count, setCount] = useState(0);
useEffect((a)= > {
if (count === 0) {
const randomNum = 10 + Math.random()*200
setCount(10 + Math.random()*200);
}
}, [count]);
return (
<div onClick={()= > setCount(0)}>{count}</div>
);
}
Copy the code
Run the component above, click div, and the page will be updated with a random number.
When you click continuously, you can see the string of numbers shaking.
The reason is that every time you click on div, count is updated to 0, and then useEffect changes count to a random number.
So the page is rendered to 0 first and then to a random number, and because the update is fast, there is a flicker.
Next we change useEffect to useLayoutEffect:
function App() {
const [count, setCount] = useState(0);
useLayoutEffect((a)= > {
if (count === 0) {
const randomNum = 10 + Math.random()*200
setCount(10 + Math.random()*200);
}
}, [count]);
return (
<div onClick={()= > setCount(0)}>{count}</div>
);
}
Copy the code
The flicker disappeared.
Instead of using useEffect, when you click on div and count is updated to 0, the page is not rendered. Instead, it waits for the internal state of useLayoutEffect to change before updating the page, so the page does not blink.
conclusion
- Compared with useEffect, useLayoutEffect can solve the problem of page flickering in some feature scenarios by synchronously executing status updates.
- UseEffect works for 99 percent of scenes, and useLayoutEffect blocks rendering, so use with caution.
Reference
When to useLayoutEffect Instead of useEffect