Difference Between useEffect and useLayoutEffect
Both useEffect
and useLayoutEffect
are hooks in React that allow you to run side-effects in function components.
The main difference between them is the timing of when they run.
useEffect
runs after the browser has painted, meaning that it's not blocking the browser from rendering the page. This is useful for any side-effects that don't need to block the rendering process, such as fetching data from an API, logging, or updating state.
useLayoutEffect
runs before the browser has painted, meaning that it can potentially block the browser from rendering the page. This can be useful for side-effects that need to be done before the browser paints, such as measuring the size of an element or updating the DOM in a way that affects layout.
Here’s an example to illustrate the difference:
import { useState, useEffect, useLayoutEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('useEffect', count);
}, [count]);
useLayoutEffect(() => {
console.log('useLayoutEffect', count);
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}