Let's explore React’s useEffect
and useLayoutEffect
Hooks, such as how they handle heavy computations and inconsistent visual changes
What is the useEffect
Hook?
The useEffect
Hook is a powerful tool in React that helps developers manage side effects in functional components. It runs asynchronously after the browser repaints the screen.
What is the useLayoutEffect
Hook?
The useLayoutEffect
Hook is a variation of the useEffect
Hook that runs synchronously before the browser repaints the screen. It was designed to handle side effects that require immediate DOM layout updates.
useLayoutEffect
is a variation of the useEffect
Hook, the signatures for both are exactly the same:
useEffect(() => {
// do something
}, [dependencies])
useLayoutEffect(() => {
// do something
}, [dependencies])
Keep in Mind:
According to the official docs for useEffect -
“Even if your Effect was caused by an interaction (like a click), the browser may repaint the screen before processing the state updates inside your Effect.”
What’s the difference between useEffect
and useLayoutEffect
?
Let's see for this code -
function Counter(){
const [count, setCount] = useState(0)
useEffect(() => {
// perform side effect
sendCountToServer(count)
}, [count])
return (
<div>
<h1> {`The current count is ${count}`} </h1>
<button onClick={() => setCount(count => count + 1)}>
Update Count
</button>
</div>
);
}
// render Counter
<Counter />
Example :
useEffect -
output -
useLayoutEffect
output -
useLayoutEffect makes the screen visually consistent. But it may cause performance issue.
When to use useEffect
and when to use useLayoutEffect
Most of the time, the useEffect
Hook should be your first choice because it runs asynchronously and doesn’t block the browser painting process, which can slow down your application. However, when you are completely sure that the code that you wish to use will visually affect your application, such as when using animations, transitions, or when you see some visual inconsistencies, use the useLayoutEffect
Hook instead.