How To Use useLayoutEffect Hook In React? See Example

useLayoutEffect is similar to useEffect but runs synchronously after DOM updates.
It’s useful for reading layout, calculating measurements, or synchronizing DOM changes.


Basic Syntax

useLayoutEffect(() => {
  // effect logic
  return () => {
    // cleanup
  };
}, [dependencies]);

Example

import React, { useState, useLayoutEffect, useRef } from "react";

function App() {
  const [width, setWidth] = useState(0);
  const boxRef = useRef();

  useLayoutEffect(() => {
    setWidth(boxRef.current.offsetWidth);
  }, []);

  return (
    <div>
      <div ref={boxRef} style={{ width: "300px", height: "100px", background: "lightblue" }} />
      <p>Box width: {width}px</p>
    </div>
  );
}

export default App;

useLayoutEffect ensures width is measured before paint, preventing flickers.


Key Points

  • Runs synchronously after DOM mutations
  • Prevents visual layout flicker
  • Ideal for measuring or manipulating DOM
  • Cleanup function works like useEffect

Conclusion

useLayoutEffect is perfect for layout-dependent operations, giving precise control over DOM updates in React apps.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *