React useLayoutEffect
Created By: chatGPT
useLayoutEffect
is a Hook in React that allows you to run side effects after the DOM has been updated, but before the browser has painted. This makes it ideal for situations where you need to read the layout of the DOM and make synchronously necessary updates. It behaves similarly to useEffect
, but it fires synchronously after all DOM mutations. It is particularly useful for measuring the layout and applying styles based on those measurements before the browser renders the updates on the screen.import React, { useLayoutEffect, useRef } from 'react';
const LayoutComponent = () => {
const divRef = useRef(null);
useLayoutEffect(() => {
const div = divRef.current;
const { width, height } = div.getBoundingClientRect();
console.log(`Width: ${width}, Height: ${height}`);
// You can modify styles or state here based on the dimensions.
});
return (
<div ref={divRef} style={{ width: '50%', height: '100px', backgroundColor: 'lightblue' }}>
Resize me!
</div>
);
};
export default LayoutComponent;
In this example, we are using
useLayoutEffect
to measure the dimensions of a div after it has been rendered in the DOM. The ref
is created using useRef
, pointing to the div element. After each render, useLayoutEffect
will log the width and height of the div, allowing you to perform logic based on these measurements.import React from 'react';
import LayoutComponent from './LayoutComponent';
const App = () => {
return (
<div>
<h1>Using useLayoutEffect Example</h1>
<LayoutComponent />
</div>
);
};
export default App;