useLayoutEffect
https://frontendmasters.com/courses/intermediate-react-v2/uselayouteffect/
useLayoutEffect
It's useful when you need to measure things in the DOM. (getBoundClientRect
, etc).
//****useLayoutEffect.js****
import React, { useState, useLayoutEffect, useRef } from "react";
const LayoutEffectComponent = () => {
const [width, setWidth] = useState(0);
const [height, setHeight] = useState(0);
// **** 2. storing the measurements here. ↴
const el = useRef();
// **** 1. we're measuring the elements here. ↴
// **** 4. it actually kicks off another rerender. ↴
// it calls the LayoutEffectComponent twice,
// but actually only paints once
useLayoutEffect(() => {
setWidth(el.current.clientWidth);
setHeight(el.current.clientHeight);
});
// useLayoutEffect works just like any other Effect
// you could do
// }, [])
// to add dependencies
return (
<div>
<h1>useLayoutEffect Example</h1>
<h2>textarea width: {width}px</h2>
<h2>textarea height: {height}px</h2>
<textarea
onClick={() => {
// **** 3. we're setting unintuitively to 0 . ↴
// has no meaning,
// but it kicks off the rerender
setWidth(0);
}}
// this will store the actual DOM element
// console.log(el)
// would show the actual textarea element
ref={el}
/>
</div>
);
};
export default LayoutEffectComponent;
The difference between useEffect and useLayoutEffect
useEffect
is (technically) asynchronous, it happens sometime after the rendering, while useLayoutEffect
is more synchronous, as it's triggered right after the rendering has taken place.
(notice the word technically, the difference is still very small)