useLayoutEffect

by Matt Tyson

HTML

<div id="root" />

CSS

input {
  width: 200px;
  border: 1px solid #ccc;
  padding: 10px;
  font-size: 16px;
}

button {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 10px;
  cursor: pointer;
  margin: 10px;
}

div {
  font-size: 20px;
  margin-top: 10px;
  font-family: Fira Code, Consolas, Source Code Pro, monospace;
}

React

const { useState, useRef, useLayoutEffect } = React;

const App = () => {
  const [width, setWidth] = React.useState(null);
  const elementRef = React.useRef(null);

  useLayoutEffect(() => {
    if (elementRef.current) {
      const { width } = elementRef.current.getBoundingClientRect();
      setWidth(width);
    }
  }, []);

  return (
    <div>
      <div ref={elementRef}>Measure Width</div>
      <p>Width: {width}</p>
    </div>
  );
};


const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <App />
);