In React, useEffect
and useLayoutEffect
are two hooks used to handle side effects in functional components. While they share similarities, there are key differences in their timing, behavior, and use cases.
useEffect
: Executes after the browser has painted the UI (asynchronous).useLayoutEffect
: Executes before the browser paints, right after DOM changes (synchronous).useEffect
: Non-blocking, runs asynchronously.useLayoutEffect
: Blocking, runs synchronously.import React, { useEffect, useLayoutEffect } from 'react';
function Example() {
const ref = React.createRef();
useEffect(() => {
console.log('useEffect: Runs after DOM paint');
});
useLayoutEffect(() => {
console.log('useLayoutEffect: Runs before DOM paint');
console.log('Element width:', ref.current.offsetWidth);
}, []);
return <div ref={ref}>Hello</div>;
}
In this example, useLayoutEffect
runs synchronously after the DOM mutation and before painting, allowing access to layout properties like offsetWidth
before the screen is updated. On the other hand, useEffect
runs asynchronously after the paint, making it suitable for non-blocking side effects.
useEffect
is ideal for asynchronous tasks like data fetching or logging, while useLayoutEffect
is suitable for synchronous operations that require immediate DOM access before painting. Understanding when to use each helps build more efficient and responsive React components.