useLayoutEffect
The function of the hook function useEffect
is the same as that of the hook function. The main differences between them are:
1. useEffect
The hook function is asynchronous, because when this function is executed, it first calculates the changes of all Dom nodes and then renders the corresponding Dom nodes to the screen. However, there may be some in the useEffect function that are still in the background. The running code, the running of these background codes and the rendering of the Dom do not affect each other, so it is possible that elements will jitter in the page rendering effect.
2. useLayoutEffect
The hook function is synchronous and will have poor performance, but it will wait until all calculations are completed and all codes are completed before rendering the Dom node.
Specific examples are as follows:
const UseLayoutEffectDemo: React.FC = () => {
const [show, setShow] = useState<boolean>(false);
const popup = useRef<HTMLDivElement>(null);
const button = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (popup.current === null || button.current === null) {
return;
} else {
const {
bottom } = button.current.getBoundingClientRect();
popup.current.style.top = `${
bottom + 25}px`;
}
});
return (
<div>
<button ref={
button} onClick={
() => setShow((prev) => !prev)}>
切换状态
</button>
{
show && (
<div style={
{
position: "absolute" }} ref={
popup}>
这是显示内容
</div>
)}
</div>
);
};
After running the above code, when you click 切换状态
the status button, 这是显示内容
the div element will first be displayed behind the button, but will soon be offset downwards by a distance of 25px. Because when show
the change occurs, the div has already started to display, and then useEffect
it starts executing the code after detecting the change. After the execution is completed, the Dom will be re-rendered. In this way, the div element will jitter, but the jitter occurs very quickly.
In order to prevent the above situation from happening, we can change useEffect
the hook function to useLayoutEffect
a hook function, so that the rendering of the Dom will wait until all related operations are completed before rendering the Dom.