useLayoutEffect Hook in React JS – Complete Detailed Notes
The useLayoutEffect Hook is a built-in React Hook used to perform layout measurements and synchronize visual changes before the browser repaints the screen. It is especially useful when a component needs to measure an element's width, height, or position and adjust its layout without showing a visible flicker.
For example, a tooltip may need to measure its own height before deciding whether to appear above or below a button. The useLayoutEffect Hook allows React to measure the tooltip and update its position before the browser displays the final result.
In most situations, useEffect is the preferred option. Use useLayoutEffect when the work must happen before the browser paints the screen. Read the official React documentation.
1. What Is the useLayoutEffect Hook?
Definition: useLayoutEffect is a React Hook that runs its setup function after React commits changes to the DOM but before the browser repaints the screen.
It allows developers to measure rendered elements, read layout information, and synchronously update layout-related state before the user sees the result.
Key Features
- Runs after React updates the DOM and before the browser repaints.
- Can measure element dimensions and positions.
- Can help prevent visual flickering during layout adjustments.
- Supports a cleanup function when required.
- Accepts a dependency array to control when the Effect runs.
- Runs only on the client, not during server rendering.
- Can block browser painting, so excessive use may reduce performance.
2. Syntax of useLayoutEffect
import { useLayoutEffect } from 'react';
useLayoutEffect(() => {
// Read layout information or synchronize visual changes
return () => {
// Optional cleanup logic
};
}, [dependencies]);
Syntax Explanation
- useLayoutEffect: The React Hook used for layout-sensitive synchronization.
- Setup function: Contains code that runs after the DOM commit and before the browser repaints.
- Cleanup function: Optionally removes listeners, cancels work, or reverses setup when necessary.
- Dependencies: Reactive values that determine when React must run the Effect again.
3. How useLayoutEffect Works
The useLayoutEffect Hook works as part of React's rendering process. It is useful when a component must inspect the actual DOM layout before the browser displays the updated screen.
- Render: React executes the component and calculates its UI.
- DOM commit: React applies the required changes to the DOM.
- Layout Effect: React runs useLayoutEffect before the browser repaints.
- Measure: The Effect reads information such as width, height, or position.
- Update: If necessary, the Effect updates state to correct the layout.
- Final render: React commits the updated result, and the browser displays the screen.
This sequence can help ensure that the user sees the final layout instead of a temporary, incorrectly positioned element.
4. Basic Example of useLayoutEffect
The following example measures the width of a heading after it has been added to the DOM.
import { useLayoutEffect, useRef, useState } from 'react';
function HeadingWidth() {
const headingRef = useRef(null);
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
if (headingRef.current) {
const measuredWidth =
headingRef.current.getBoundingClientRect().width;
setWidth(measuredWidth);
}
}, []);
return (
<div>
<h2 ref={headingRef}>Welcome to React JS</h2>
<p>Heading width: {width.toFixed(2)} pixels</p>
</div>
);
}
export default HeadingWidth;
Explanation
useRef creates a reference to the heading DOM element.
- The
ref attribute connects the DOM element to headingRef.
getBoundingClientRect() returns the element's size and position.
useLayoutEffect reads the width before the browser repaints.
setWidth updates the state with the measured width.
- The component displays the measured width in pixels.
Important: This example demonstrates layout measurement. If the width does not need to affect the first visible layout, an ordinary useEffect or a CSS-based solution may be sufficient.
5. Understanding useLayoutEffect Dependencies
The dependency array determines when React reruns the layout Effect. React compares each dependency with its previous value using Object.is.
| Dependency Array |
Behavior |
[] |
Runs after the initial client-side commit. Cleanup runs when the component is removed. |
[width] |
Runs after the initial commit and again when width changes. |
[width, height] |
Runs after the initial commit and when either dependency changes. |
| No dependency array |
Runs after every commit of the component. |
Example With a Dependency
import { useLayoutEffect, useRef, useState } from 'react';
function BoxMeasurement() {
const boxRef = useRef(null);
const [boxWidth, setBoxWidth] = useState(200);
useLayoutEffect(() => {
if (boxRef.current) {
const width =
boxRef.current.getBoundingClientRect().width;
console.log('Current box width:', width);
}
}, [boxWidth]);
return (
<div>
<div
ref={boxRef}
style={{
width: `${boxWidth}px`,
height: '100px',
backgroundColor: 'lightblue'
}}
>
Measurable Box
</div>
<button onClick={() => setBoxWidth(300)}>
Increase Width
</button>
</div>
);
}
export default BoxMeasurement;
Explanation: The Effect measures the box after the initial commit and whenever boxWidth changes. When the button changes the width, React commits the updated box, and the Effect reads its new dimensions.
6. useLayoutEffect With useRef
The useRef Hook is commonly used with useLayoutEffect because it provides access to a DOM element after React has committed it to the page.
Common DOM Measurements
const rect = element.getBoundingClientRect();
console.log(rect.width);
console.log(rect.height);
console.log(rect.top);
console.log(rect.left);
console.log(rect.bottom);
console.log(rect.right);
The getBoundingClientRect() method returns a rectangle describing an element's size and position relative to the viewport.
Example: Measure a Box
import { useLayoutEffect, useRef, useState } from 'react';
function MeasureBox() {
const boxRef = useRef(null);
const [dimensions, setDimensions] = useState({
width: 0,
height: 0
});
useLayoutEffect(() => {
const box = boxRef.current;
if (!box) return;
const rect = box.getBoundingClientRect();
setDimensions({
width: rect.width,
height: rect.height
});
}, []);
return (
<div>
<div
ref={boxRef}
style={{
width: '250px',
height: '120px',
padding: '10px',
border: '2px solid black'
}}
>
Measure this box
</div>
<p>Width: {dimensions.width}px</p>
<p>Height: {dimensions.height}px</p>
</div>
);
}
export default MeasureBox;
7. Practical Example: Positioning a Tooltip
A tooltip is a small message displayed near an element. Sometimes there is not enough space above the element, so the tooltip must appear below it instead.
We can use useLayoutEffect to measure the tooltip's height and determine its position before the browser repaints.
import { useLayoutEffect, useRef, useState } from 'react';
function TooltipExample() {
const tooltipRef = useRef(null);
const [position, setPosition] = useState('above');
useLayoutEffect(() => {
const tooltip = tooltipRef.current;
if (!tooltip) return;
const rect = tooltip.getBoundingClientRect();
if (rect.top < 0) {
setPosition('below');
} else {
setPosition('above');
}
}, []);
return (
<div style={{ paddingTop: '80px' }}>
<button>Hover Target</button>
<div
ref={tooltipRef}
style={{
position: 'relative',
marginTop: '10px',
padding: '10px',
backgroundColor: '#222',
color: '#fff',
width: '180px'
}}
>
Tooltip appears {position}
</div>
</div>
);
}
export default TooltipExample;
Explanation: The component measures the tooltip's position and selects a position based on its location. This simplified example demonstrates measurement; a production tooltip should also account for the target element's position, viewport boundaries, scrolling, resizing, and whether the tooltip is actually open.
8. useLayoutEffect vs useEffect
Both Hooks synchronize React components with external systems, but their timing is different. The key difference is whether the Effect must run before the browser repaints.
| Feature |
useLayoutEffect |
useEffect |
| Timing |
After the DOM commit and before browser repaint. |
Usually after the browser paints when the Effect is not caused by an interaction; exact scheduling can vary. |
| Primary purpose |
Layout measurement and visual synchronization. |
Synchronization with external systems such as subscriptions, timers, and network connections. |
| Blocks painting |
Yes, its work and synchronous state updates can block repainting. |
Does not normally block the browser from painting. |
| Performance impact |
Can slow rendering if used excessively. |
Usually preferred for non-layout Effects. |
| Typical examples |
Measuring a tooltip or adjusting layout before display. |
Fetching data, subscribing to events, or connecting to external services. |
| Server rendering |
Does not run on the server. |
Does not run on the server. |
Example of useEffect
import { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const timerId = setInterval(() => {
setSeconds(previous => previous + 1);
}, 1000);
return () => {
clearInterval(timerId);
};
}, []);
return <p>Seconds: {seconds}</p>;
}
export default Timer;
This timer synchronizes with an external browser timer and does not require measuring or correcting the layout before paint. Therefore, useEffect is the appropriate choice.
When Should You Choose useLayoutEffect?
- When an element's dimensions must be measured before the user sees the updated screen.
- When a tooltip, popover, or overlay must be positioned accurately on its first visible frame.
- When a visual adjustment made after paint would cause a noticeable flicker.
- When synchronizing a layout-sensitive third-party widget that requires immediate DOM measurements.
When Should You Choose useEffect?
- When fetching data or subscribing to an external service.
- When setting up timers or event listeners that do not require a pre-paint layout update.
- When synchronizing with a non-visual external system.
- Whenever the Effect does not need to block the browser from painting.
9. useLayoutEffect With State Updates
Calling a state setter inside useLayoutEffect can cause React to render again before the browser repaints. This is useful when the new state corrects a visual measurement, but it should be used carefully.
import { useLayoutEffect, useRef, useState } from 'react';
function DynamicPanel() {
const panelRef = useRef(null);
const [height, setHeight] = useState(0);
useLayoutEffect(() => {
if (panelRef.current) {
const measuredHeight =
panelRef.current.getBoundingClientRect().height;
setHeight(measuredHeight);
}
}, []);
return (
<div>
<div ref={panelRef}>
<p>This is a dynamic panel.</p>
<p>Its height is measured after mounting.</p>
</div>
<p>Measured height: {height}px</p>
</div>
);
}
export default DynamicPanel;
React measures the panel and updates the height state before the browser repaints. React may perform an additional render to display the updated measurement.
Performance warning: Repeated measurements and state updates can slow the interface. Only measure and update state when the measurement is genuinely needed.
10. Cleanup Function in useLayoutEffect
A cleanup function is returned from the setup function when an Effect needs to undo its work. React runs cleanup before rerunning an Effect with changed dependencies and when the component is removed.
import { useLayoutEffect, useRef } from 'react';
function ElementObserver() {
const boxRef = useRef(null);
useLayoutEffect(() => {
const box = boxRef.current;
if (!box) return;
function handleResize() {
console.log('Window resized');
}
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return <div ref={boxRef}>Resize the browser window</div>;
}
export default ElementObserver;
This example uses a layout Effect for demonstration, but a normal useEffect is usually sufficient for a window resize listener when it does not need to block painting.
11. Common Mistakes When Using useLayoutEffect
Mistake 1: Using useLayoutEffect for Every Effect
Problem: Layout Effects can block the browser from repainting, increasing the time before content becomes visible.
Solution: Prefer useEffect unless the work must happen before paint.
Mistake 2: Forgetting the Dependency Array
// Runs after every component commit
useLayoutEffect(() => {
console.log('Layout Effect ran');
});
Solution: Provide the appropriate dependency array and include all reactive values used by the Effect.
Mistake 3: Accessing a DOM Element Before It Exists
useLayoutEffect(() => {
console.log(boxRef.current.getBoundingClientRect());
}, []);
Problem: The ref may be null in situations where the element is not mounted or rendered conditionally.
Solution: Check that the ref exists before measuring it.
useLayoutEffect(() => {
const box = boxRef.current;
if (!box) return;
console.log(box.getBoundingClientRect());
}, []);
Mistake 4: Creating an Infinite Update Cycle
If a layout Effect updates state and that state causes the Effect's dependencies to change repeatedly, the component can enter a repeated update cycle.
Solution: Review the dependency array, ensure the state update is necessary, and avoid repeatedly setting state to equivalent measurements when it is not needed.
Mistake 5: Ignoring Cleanup
Event listeners, observers, and other resources may remain active if cleanup is omitted.
Solution: Remove listeners or disconnect observers in the cleanup function when necessary.
Mistake 6: Expecting It to Run During Server Rendering
useLayoutEffect requires browser layout information, which is not available during server rendering.
Solution: Use useEffect when appropriate, render layout-dependent components only on the client when necessary, or provide a suitable server-rendering strategy.
12. Rules of the useLayoutEffect Hook
- Import useLayoutEffect from React.
- Call it only at the top level of a function component or Custom Hook.
- Do not call it inside conditions, loops, or nested functions.
- Specify every reactive dependency used by the Effect.
- Use a cleanup function when the setup requires cleanup.
- Remember that it runs only on the client.
- Use it for layout-sensitive work rather than general-purpose logic.
- Keep the Effect's work small to reduce blocking time.
- Expect an additional setup and cleanup cycle in development when Strict Mode is enabled.
13. useLayoutEffect and Server-Side Rendering
Server-side rendering creates HTML without a browser layout. Since useLayoutEffect is designed to work with client-side DOM layout, it does not run on the server.
When a component requires layout information to display correctly, consider these options:
- Use useEffect if it is acceptable for the initial content to appear before the Effect runs.
- Render the layout-dependent component only on the client when that matches the application design.
- Provide an appropriate fallback or loading state for server-rendered output.
- Consider whether CSS can solve the layout problem without JavaScript measurement.
Do not replace useLayoutEffect with useEffect automatically if doing so introduces a visible layout shift. Choose the approach that matches the rendering requirements.
14. Advantages of useLayoutEffect
- Allows layout measurement before browser repaint.
- Helps prevent visible flicker in certain visual adjustments.
- Provides access to DOM dimensions and positions after the DOM commit.
- Supports layout-sensitive UI such as tooltips, popovers, and overlays.
- Can synchronize visual state with DOM measurements.
15. Limitations of useLayoutEffect
- Can block browser painting and affect performance.
- Does not run during server rendering.
- May cause extra renders when state is updated inside the Effect.
- Requires careful dependency management.
- Can be unnecessary when CSS or useEffect can solve the problem.
- Needs careful handling when elements are conditionally rendered or their layout changes dynamically.
16. Practical Project: Responsive Element Measurement
In this project, create a component that measures an element's dimensions when it mounts and whenever the browser window is resized. The example uses useLayoutEffect and a resize event listener.
import { useLayoutEffect, useRef, useState } from 'react';
function ResponsiveMeasurement() {
const elementRef = useRef(null);
const [size, setSize] = useState({
width: 0,
height: 0
});
useLayoutEffect(() => {
const element = elementRef.current;
if (!element) return;
function measureElement() {
const rect = element.getBoundingClientRect();
setSize(previous => {
if (
previous.width === rect.width &&
previous.height === rect.height
) {
return previous;
}
return {
width: rect.width,
height: rect.height
};
});
}
measureElement();
window.addEventListener('resize', measureElement);
return () => {
window.removeEventListener('resize', measureElement);
};
}, []);
return (
<div>
<div
ref={elementRef}
style={{
width: '80%',
minHeight: '100px',
padding: '20px',
border: '2px solid steelblue',
boxSizing: 'border-box'
}}
>
Resize the browser to measure this element.
</div>
<p>Width: {size.width.toFixed(1)}px</p>
<p>Height: {size.height.toFixed(1)}px</p>
</div>
);
}
export default ResponsiveMeasurement;
Project Explanation
- The component creates a ref for the element being measured.
- The layout Effect reads the element's dimensions.
- The measurement is stored in state.
- A resize listener measures the element again when the browser window changes size.
- The cleanup function removes the resize listener when the component is removed.
- The component displays the current width and height.
Note: For production applications, a ResizeObserver is often more appropriate when you need to detect changes to an element's dimensions regardless of what caused them. A resize listener only observes changes to the browser window, not every possible element-size change.
17. Frequently Asked Interview Questions
Q1. What is useLayoutEffect in React?
useLayoutEffect is a React Hook that runs after DOM changes are committed but before the browser repaints the screen.
Q2. Why is useLayoutEffect used?
It is used for layout-sensitive tasks such as measuring DOM elements and correcting their visual position before they appear to the user.
Q3. What is the difference between useLayoutEffect and useEffect?
useLayoutEffect runs before browser repaint and can block painting, while useEffect usually runs after painting for Effects that are not caused by an interaction. useEffect is preferred when pre-paint execution is unnecessary.
Q4. Can useLayoutEffect access DOM elements?
Yes. It is commonly used with useRef to read the dimensions and position of committed DOM elements.
Q5. Does useLayoutEffect run on the server?
No. It runs only on the client because server rendering does not provide browser layout information.
Q6. Can useLayoutEffect update state?
Yes. A state update inside the Hook can cause React to render again before the browser repaints.
Q7. Why can useLayoutEffect affect performance?
Its work and synchronous state updates can block browser painting, delaying the display of the updated screen.
Q8. What is the purpose of the dependency array?
The dependency array specifies the reactive values that determine when the Effect must run again.
Q9. Can useLayoutEffect return a cleanup function?
Yes. The cleanup function can remove event listeners, disconnect observers, or undo other setup work.
Q10. When should useEffect be preferred?
Use useEffect for most synchronization tasks that do not need to block browser painting, such as subscriptions, timers, and non-visual external systems.
Q11. What is getBoundingClientRect()?
It is a browser DOM method that returns an element's size and position relative to the viewport.
Q12. What happens in React Strict Mode?
In development, Strict Mode performs an extra setup and cleanup cycle to help detect Effects whose cleanup does not correctly undo their setup.
18. Practice Exercises
- Create a component that measures the width of a heading using useLayoutEffect and useRef.
- Build a box that displays its current width and height.
- Create a tooltip that measures its height before choosing a position.
- Compare useEffect and useLayoutEffect by measuring a component's dimensions.
- Create a component that updates its layout when a measurement changes.
- Add an event listener in an Effect and remove it during cleanup.
- Experiment with an empty dependency array and a dependency array containing state.
- Use CSS to solve a layout problem that would otherwise require JavaScript measurement.
19. Quick Revision Checklist
- ☑ useLayoutEffect runs after the DOM commit but before browser repaint.
- ☑ It is useful for layout measurement and visual corrections.
- ☑ It commonly works with useRef and getBoundingClientRect().
- ☑ It accepts a setup function and an optional dependency array.
- ☑ It can return a cleanup function.
- ☑ State updates inside it may cause another render before paint.
- ☑ It can block browser painting and should be used sparingly.
- ☑ It does not run during server rendering.
- ☑ useEffect is preferred when pre-paint execution is not necessary.
- ☑ Hooks must be called at the top level of components or Custom Hooks.
20. Official React Documentation
21. React JS Training Resources
To learn more about React JS Hooks, DOM manipulation, component rendering, and performance optimization, explore the following resources:
22. Conclusion
The useLayoutEffect Hook is useful when a React component must measure the DOM or make a visual correction before the browser repaints. It is commonly used for tooltips, popovers, and layout-sensitive UI. However, because it can block painting and affect performance, use it only when pre-paint execution is necessary. For most other Effects, prefer useEffect and follow the Rules of Hooks, dependency requirements, and cleanup practices.