React useLayoutEffect
Use a layout effect for a required post-DOM measurement, and keep the work small.
How it works
useLayoutEffect runs after DOM changes but before the browser paints. It can measure a committed element when the next visual decision depends on its size. That timing blocks painting, so ordinary subscriptions and requests belong in useEffect instead. This example measures a compact notice and reports whether its width crosses a defined threshold. A ResizeObserver keeps the measurement current, and cleanup disconnects it.
Run the code
Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.
No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.
Example
import React, { StrictMode, useState, useRef, useLayoutEffect } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';
function App() {
const notice = useRef(null);
const [size, setSize] = useState('Measuring');
useLayoutEffect(() => {
const node = notice.current;
const measure = () =>
setSize(
node.getBoundingClientRect().width < 500 ? 'Compact notice' : 'Wide notice',
);
measure();
const observer = new ResizeObserver(measure);
observer.observe(node);
return () => observer.disconnect();
}, []);
return (
<main>
<h1>Neighbourhood lending desk</h1>
<section ref={notice}>
<h2>Collection desk</h2>
<p>Check the window before leaving home.</p>
</section>
<output>{size}</output>
</main>
);
}
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
);
Expected result
The narrow browser shows Compact notice and the wide browser shows Wide notice.
The threshold is an explicit lab policy, not a universal mobile breakpoint. getBoundingClientRect reads the committed box. ResizeObserver handles later size changes instead of assuming only the window can change layout. Server rendering does not provide layout measurements; a server-capable component needs a separate strategy for content that depends on browser geometry.
For API contracts and version differences, use React’s official documentation.