React
useLayoutEffect
useLayoutEffect
is pretty much the same as useEffect, it's just a little different about when the effect performs, we recommend you check out useEffect
document first before continuing. useLayoutEffect
call signature is the same as useEffect
// Calling signature
useLayoutEffect(effectFunction, arrayDependencies)
Difference between useEffect and useLayoutEffect
The function passed to useEffect
fires after the render has completed and all changes have been committed to the screen. And the side effects will NOT block the browser from updating the screen. useLayouEffect
on the other hand will fire before the browser updates the screen, it will block the browser so useLayoutEffect
only allow synchronous effect functions.
For most cases, useEffect
is preferred to useLayoutEffect
, but there are some special cases when it will cause flickers of changes in the UI, which will annoy users and you need to make a visual change to the DOM as a side effect before changes are committed to the screen. Check out the example below
function Count() {const [count1, setCount1] = useState(-1)const [count2, setCount2] = useState(-1)const [reload, setReload] = useState(false)useEffect(() => {setCount1(100)}, [reload])useLayoutEffect(() => {setCount2(100)}, [reload])const handleClick = () => {setCount1(-1)setCount2(-1)setReload(r => !r)}return (<><div>Current count1 is {count1 < 0 ? "Loading...." : count1}</div><div>Current count2 is {count2 < 0 ? "Loading...." : count2}</div><Button onClick={handleClick}>Reload</Button></>)}