| useState-vs-useReducer :👈 | 👉:useMemo in React |
useEffect vs useLayoutEffect Explained |
useEffect vs useLayoutEffect in React
1. Quick Answer
Both useEffect and useLayoutEffect are React Hooks used to synchronize a component with external systems, such as browser APIs, subscriptions, and third-party libraries. They differ mainly in when their effects run relative to the browser painting the screen.
- useEffect: Runs after React commits changes to the DOM. React generally allows the browser to paint before running effects that are not caused by an interaction, so this is the preferred hook for most side effects.
- useLayoutEffect: Runs after React updates the DOM but before the browser paints. It is useful when you must measure or adjust layout before the user sees the result.
Rule of thumb: Use useEffect by default. Use useLayoutEffect only when work must happen before the browser paints to avoid visible layout problems.
2. Table of Contents
- Understanding React Rendering
- What Is useEffect?
- What Is useLayoutEffect?
- Execution Order and Differences
- Example: Measuring a DOM Element
- Example: Preventing Visual Flicker
- Dependency Arrays and Cleanup
- When to Use Each Hook
- Common Mistakes
- Performance Considerations
- Best Practices
- Interview Questions
- Summary
3. Understanding React Rendering
When a React component's state or props change, React renders the component and commits the necessary changes to the DOM. The browser then paints the updated screen.
React effects let a component synchronize with something outside React, such as a timer, an event listener, a network connection, or a DOM measurement.
Typical Rendering Flow
Important: This is a simplified illustration. The exact scheduling of useEffect depends on how the update was triggered and React's scheduling behavior. Effects caused by interactions may run before the browser paints. Do not rely on useEffect always running after paint.
4. What Is useEffect?
useEffect is a React Hook that lets a component synchronize with an external system. It is commonly used for fetching data, subscriptions, timers, event listeners, and updating external browser APIs.
Syntax
useEffect(() => {
// Synchronize with an external system.
return () => {
// Optional cleanup.
};
}, [dependencies]);
- The effect function runs after React commits the component's changes.
- The dependency array determines when React needs to run the effect again.
- The cleanup function runs before the effect is set up again with changed dependencies and when the component is removed.
Example 1: Updating the Document Title
import { useEffect, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default Counter;
Whenever count changes, React commits the update and the effect synchronizes the browser tab's title with the current count.
Example 2: Setting Up an Event Listener
import { useEffect, useState } from "react";
function WindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
return <p>Window width: {width}px</p>;
}
export default WindowWidth;
The effect registers a resize listener. Its cleanup removes the listener when the component is removed.
Server-rendering note: The initial use of window.innerWidth assumes a browser environment. In an application that renders components on the server, access browser-only APIs in client-side code and account for the initial server-rendered output.
5. What Is useLayoutEffect?
useLayoutEffect has a similar API to useEffect, but it runs after React commits DOM changes and before the browser repaints the screen.
This makes it useful when an effect must read layout information and synchronously update the DOM or React state before the user sees the result.
Syntax
useLayoutEffect(() => {
// Measure or synchronously adjust layout before paint.
return () => {
// Optional cleanup.
};
}, [dependencies]);
Example: Measuring an Element
import { useLayoutEffect, useRef, useState } from "react";
function ElementMeasurement() {
const boxRef = useRef(null);
const [height, setHeight] = useState(0);
useLayoutEffect(() => {
if (boxRef.current) {
const rect = boxRef.current.getBoundingClientRect();
setHeight(rect.height);
}
}, []);
return (
<div>
<div ref={boxRef}>
Measure this element.
</div>
<p>Height: {height}px</p>
</div>
);
}
export default ElementMeasurement;
How It Works
- React renders the component.
- React commits the DOM element.
useLayoutEffectreads the element's dimensions.- The effect updates the height state if necessary.
- React can render and commit the updated output before the browser paints.
This can prevent the user from seeing an intermediate layout. However, the measurement in this example is only taken on mount. If the element can resize later, use an appropriate resize strategy, such as ResizeObserver, and clean it up correctly.
6. useEffect vs useLayoutEffect: Key Differences
| Feature | useEffect | useLayoutEffect |
|---|---|---|
| When it runs | After the DOM commit; React generally lets the browser paint first for effects not caused by an interaction. | After the DOM commit but before the browser paints. |
| Typical purpose | Synchronizing with external systems. | Measuring layout or making visual corrections before paint. |
| Browser painting | Often does not block the initial paint. | Blocks painting until the effect and any synchronous updates it triggers are processed. |
| Performance | Usually preferred because it avoids unnecessarily blocking paint. | Can delay visible rendering if the effect does expensive work. |
| Data fetching | Usually appropriate. | Usually unnecessary. |
| Event listeners and subscriptions | Usually appropriate. | Only when a specific pre-paint requirement exists. |
| DOM measurements | May be suitable if a post-paint measurement is acceptable. | Useful when the measurement must affect the layout before the user sees it. |
| Server rendering | Does not run during server rendering. | Does not run during server rendering and may produce a warning when used in server-rendered components. |
7. Example: Measuring a DOM Element
Suppose you want to display a tooltip above a button. You need to measure the button's position and calculate the tooltip's location.
Using useEffect
import { useEffect, useRef, useState } from "react";
function Tooltip() {
const buttonRef = useRef(null);
const [position, setPosition] = useState({ top: 0, left: 0 });
useEffect(() => {
if (!buttonRef.current) return;
const rect = buttonRef.current.getBoundingClientRect();
setPosition({
top: rect.top - 40,
left: rect.left
});
}, []);
return (
<div>
<button ref={buttonRef}>Hover here</button>
<div
style={{
position: "fixed",
top: position.top,
left: position.left
}}
>
Tooltip
</div>
</div>
);
}
export default Tooltip;
Depending on the rendering and scheduling, the user may briefly see the tooltip at its initial position before React applies the measured position.
Using useLayoutEffect
import { useLayoutEffect, useRef, useState } from "react";
function Tooltip() {
const buttonRef = useRef(null);
const [position, setPosition] = useState({ top: 0, left: 0 });
useLayoutEffect(() => {
if (!buttonRef.current) return;
const rect = buttonRef.current.getBoundingClientRect();
setPosition({
top: rect.top - 40,
left: rect.left
});
}, []);
return (
<div>
<button ref={buttonRef}>Hover here</button>
<div
style={{
position: "fixed",
top: position.top,
left: position.left
}}
>
Tooltip
</div>
</div>
);
}
export default Tooltip;
Which is better? If the tooltip must be positioned correctly before it first becomes visible, useLayoutEffect is more suitable. In a real tooltip, also account for viewport boundaries, scrolling, resizing, and changes to the button's position.
8. Example: Preventing Visual Flicker
Imagine a navigation menu whose items must be measured to determine which items fit on the screen. An initial render may show all items, followed by an update that hides the items that do not fit.
With useEffect, the browser may paint the initial menu before the calculation runs. This can cause a brief visual flicker.
With useLayoutEffect, the component can measure the items and update the layout before the browser paints, avoiding that intermediate visible state.
Important Considerations
- Use
useLayoutEffectonly if the intermediate visual state is a problem. - Keep the measurement and update work small.
- Consider CSS layout techniques when they can solve the problem without JavaScript.
- Do not use
useLayoutEffectsimply because it sounds more precise.
9. Dependency Arrays and Cleanup
Both hooks use dependency arrays in the same way.
No Dependency Array
useEffect(() => {
console.log("Runs after every committed render");
});
Without a dependency array, the effect runs after every committed render.
Empty Dependency Array
useEffect(() => {
console.log("Runs when this effect is mounted");
return () => {
console.log("Cleanup");
};
}, []);
The effect is set up when the component mounts. Its cleanup runs when the component is removed. In development Strict Mode, React may perform an additional setup-and-cleanup cycle to help reveal bugs.
Dependency Array With Values
useEffect(() => {
console.log("Current user:", userId);
}, [userId]);
The effect runs after the initial commit and again when userId changes.
Cleanup Example: Timer
import { useEffect, useState } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const timerId = setInterval(() => {
setSeconds(current => current + 1);
}, 1000);
return () => {
clearInterval(timerId);
};
}, []);
return <p>Seconds: {seconds}</p>;
}
export default Timer;
For this timer, useEffect is the appropriate choice. There is no need to block the browser from painting.
10. When to Use Each Hook
Use useEffect For
- Fetching data from an API.
- Subscribing to an external data source.
- Registering and removing event listeners.
- Setting up timers and intervals.
- Synchronizing with browser APIs when pre-paint execution is unnecessary.
- Connecting to third-party services or widgets.
Use useLayoutEffect For
- Measuring an element before the browser paints.
- Positioning a tooltip or popover before it becomes visible.
- Reading layout values to make a synchronous visual correction.
- Integrating with a library that requires DOM measurements before paint.
Do Not Use Either Hook When
- You can calculate a value directly from props or state during rendering.
- You can handle an operation directly in an event handler.
- You only need to initialize state from a known initial value.
- CSS can solve a visual layout problem without JavaScript.
Example: Avoid an Unnecessary Effect
Unnecessary:
const [firstName, setFirstName] = useState("Sam");
const [lastName, setLastName] = useState("Smith");
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(`${firstName} ${lastName}`);
}, [firstName, lastName]);
Better:
const [firstName, setFirstName] = useState("Sam");
const [lastName, setLastName] = useState("Smith");
const fullName = `${firstName} ${lastName}`;
The full name is derived from existing state, so storing it separately and synchronizing it through an effect creates unnecessary complexity and an extra update.
11. Common Mistakes
Mistake 1: Using useLayoutEffect for Everything
useLayoutEffect blocks browser painting until its work is complete. Using it for API calls, timers, or ordinary subscriptions can unnecessarily delay rendering.
Solution: Prefer useEffect unless you have a specific pre-paint requirement.
Mistake 2: Assuming useEffect Always Runs After Paint
React generally allows the browser to paint before running effects that are not caused by an interaction. However, effects associated with interactions may run before paint. Avoid depending on an absolute paint-order guarantee for useEffect.
Mistake 3: Forgetting Dependencies
useEffect(() => {
console.log(userId);
}, []);
If the effect is supposed to react to changes in userId, omitting it from the dependency array can cause the effect to use a stale value.
Solution: Include the reactive values used by the effect and follow the React Hooks lint rules.
Mistake 4: Creating an Infinite Update Loop
useEffect(() => {
setCount(count + 1);
}, [count]);
The effect updates count, which changes a dependency and causes the effect to run again. This can create an endless update loop.
Solution: If the update belongs to a user action, perform it in the event handler. If an effect is needed, ensure the synchronization logic has an appropriate stopping condition.
Mistake 5: Reading Layout Too Early
DOM measurement requires the element to exist in the committed DOM. Reading a ref before React has attached it can produce null.
Solution: Read the DOM element inside an appropriate effect or event handler after it has been committed, and check that the ref is available.
Mistake 6: Ignoring Server Rendering
Neither effect hook runs during server rendering. useLayoutEffect can also produce a warning when a component is rendered on the server because its intended work cannot happen there.
Solution: If the component requires browser layout information, render it only on the client when appropriate, or redesign it so the server-rendered output does not depend on layout measurements.
12. Performance Considerations
- Prefer useEffect: It is the right default for most synchronization tasks.
- Keep layout effects small: Long-running synchronous work delays browser painting.
- Avoid unnecessary state updates: Every extra update may cause additional rendering work.
- Measure before optimizing: Use browser performance tools and React DevTools to identify actual rendering bottlenecks.
- Prefer CSS when possible: CSS layout and positioning can often eliminate JavaScript measurement and visual corrections.
- Use ResizeObserver when appropriate: It can detect changes to an element's dimensions without relying only on window resize events.
13. Best Practices
- Use
useEffectas the default effect hook. - Use
useLayoutEffectonly when work must happen before paint. - Keep effect callbacks synchronous; start asynchronous operations inside them rather than making the effect callback itself an async function.
- Include the required reactive values in dependency arrays.
- Clean up subscriptions, timers, and event listeners.
- Do not use effects to calculate values that can be derived during rendering.
- Do not mutate React state or perform unrelated side effects inside effects or reducers.
- Test components in development Strict Mode to expose missing cleanup and other lifecycle issues.
- Consider server rendering and hydration when using browser-only APIs.
14. Interview Questions
Q1. What is the main difference between useEffect and useLayoutEffect?
Answer: Both run after React commits DOM changes. useLayoutEffect runs before the browser paints, while useEffect generally allows painting first for effects not caused by an interaction.
Q2. Why can useLayoutEffect cause performance problems?
Answer: It blocks browser painting until the effect and any synchronous updates it triggers are processed. Expensive work can delay the visible screen.
Q3. Should API calls use useLayoutEffect?
Answer: Usually not. API requests do not normally require pre-paint execution, so useEffect is generally more appropriate.
Q4. When is useLayoutEffect useful?
Answer: It is useful when a component needs to measure or synchronously correct the DOM layout before the user sees the result, such as positioning a tooltip.
Q5. Do these hooks run during server rendering?
Answer: No. Neither hook runs on the server. Components that depend on browser layout measurements may need a client-only rendering strategy.
Q6. Can useEffect cause flickering?
Answer: Yes. If an effect updates the layout after an initial paint, the user may briefly see an intermediate state. If that visual correction must happen before paint, consider useLayoutEffect.
Q7. Is useLayoutEffect always better because it runs earlier?
Answer: No. It can block painting and hurt responsiveness. Use it only when pre-paint execution is necessary.
Q8. What is the purpose of a cleanup function?
Answer: Cleanup releases resources or reverses setup work, such as removing an event listener or clearing a timer. React runs cleanup before re-running an effect with changed dependencies and when the component is removed.
15. Summary
| Requirement | Recommended Hook |
|---|---|
| Fetch data from an API | useEffect |
| Register an event listener | useEffect |
| Set up a timer | useEffect |
| Subscribe to an external service | useEffect |
| Measure a DOM element before paint | useLayoutEffect |
| Correct a visual layout before paint | useLayoutEffect |
| Calculate a value from props or state | Usually neither hook |
Final recommendation: Start with useEffect. Switch to useLayoutEffect only when you need to measure or update the layout before the browser paints and a visible intermediate state would be a problem.
| useState-vs-useReducer :👈 | 👉:useMemo in React |
Comments and Discussion