The `useLayoutEffect` hook is a powerful tool in React that allows developers to perform side effects in a way that ensures the DOM is updated synchronously before the browser has a chance to paint. This can be particularly useful for tasks that require measuring the DOM or making adjustments that need to happen immediately after the DOM updates but before the user sees the changes. Understanding when and how to use `useLayoutEffect` is crucial for optimizing performance and ensuring a smooth user experience.
Typically, `useLayoutEffect` is used in scenarios where you need to read layout from the DOM and synchronously re-render. Here are some common use cases:
When using `useLayoutEffect`, consider the following best practices:
Here are some common pitfalls to avoid when using `useLayoutEffect`:
Here’s a simple example demonstrating the use of `useLayoutEffect`:
import React, { useLayoutEffect, useRef, useState } from 'react';
const CenteredModal = () => {
const modalRef = useRef(null);
const [modalPosition, setModalPosition] = useState({ top: 0, left: 0 });
useLayoutEffect(() => {
const modal = modalRef.current;
if (modal) {
const { width, height } = modal.getBoundingClientRect();
setModalPosition({
top: (window.innerHeight - height) / 2,
left: (window.innerWidth - width) / 2,
});
}
}, []);
return (
Centered Modal
);
};
This example demonstrates how to center a modal on the screen by measuring its dimensions and adjusting its position using `useLayoutEffect`. The modal's position is calculated immediately after the DOM has been updated, ensuring a smooth user experience.