Changing Display by Element Width with ResizeObserver in React
This article was translated from the Japanese original with AI. 日本語の原文を読む
With ResizeObserver, you can change the display of a React component based on the width of the element itself, not the width of the whole screen. For example, you can show the same card side by side in a wide column and stacked vertically in a narrow sidebar. This approach is useful when you want to build a component whose width changes depending on where it is placed. The registration and cleanup of the observer are both handled inside the function passed to ref.
If you only want to change the look (CSS), you can apply styles based on the container size with CSS container queries. If you want to change the components themselves based on width (for example, whether to show a number column), receive the width in JavaScript.
The test environment was Ubuntu 24.04 and Node.js 22.22.0. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, and esbuild 0.28.2. I type-checked the .tsx files with tsc, transformed them for development with esbuild, and operated Chrome for Testing 153 (Chromium) with Playwright 1.64.1. I have not tested Firefox, Safari, or real smartphones.
ResizeObserver calls observe inside the function passed to ref, and that function returns a cleanup function that calls disconnect. If you put a layout name (such as 'wide') in state instead of the numeric width, React skips re-rendering as long as the name does not change.
- 1. A hook that receives the element width
- 2. Turning the width into a breakpoint name and switching the display
- 3. Putting a name in state, not the numeric width
- 4. Pass the ref as a function, not with
useRef - 5. Which box does the width refer to?
- 6. Do not observe an element whose width changes with its own contents
- 7. Watch the outer frame and switch by name
A hook that receives the element width
First, here is a hook that simply puts the element width into state.
import { useCallback, useState } from 'react';
// Set the element's width (content box) to state
export function useElementWidth<T extends Element>() {
const [width, setWidth] = useState<number | null>(null);
// In React 19, the function passed to ref can return a cleanup function
const ref = useCallback((el: T | null) => {
if (!el) return;
const observer = new ResizeObserver(([entry]) => {
setWidth(entry.contentBoxSize[0].inlineSize);
});
observer.observe(el);
return () => observer.disconnect();
}, []);
return [ref, width] as const;
}
Monitoring starts inside the function passed to ref (the ref callback), not in useEffect. As described in the official reference on ref callbacks, React calls this function when the DOM element is added to the screen, and calls the returned cleanup function when the element is removed. Returning a cleanup function from a ref callback is a feature introduced in React 19.
The width is read with contentBoxSize[0].inlineSize. According to the MDN page on contentBoxSize, inlineSize is the width in horizontal writing mode. The value is an array to handle cases where the element is split into multiple fragments, such as in multi-column layouts.
Turning the width into a breakpoint name and switching the display
When switching the display, a hook that returns a name matched to a breakpoint is easier to use than one that returns the raw width.
import { useCallback, useState } from 'react';
// Sort [this width or above, this name] by width in descending order. The last one is 0.
export type Breakpoints<N extends string> = readonly (readonly [minWidth: number, name: N])[];
// Return the element's width as a name based on the breakpoints
export function useWidthClass<T extends Element, N extends string>(breakpoints: Breakpoints<N>) {
const [name, setName] = useState<N | null>(null);
const ref = useCallback(
(el: T | null) => {
if (!el) return;
const observer = new ResizeObserver(([entry]) => {
const width = entry.contentBoxSize[0].inlineSize;
const hit = breakpoints.find(([min]) => width >= min) ?? breakpoints[breakpoints.length - 1];
// If the name is the same, React does not re-render
setName(hit[1]);
});
observer.observe(el);
return () => observer.disconnect();
},
[breakpoints],
);
return [ref, name] as const;
}
On the using side, you attach ref to an outer div and decide the contents based on its width. The following code is the card I used for testing. If the width is 480px or more, the card is laid out side by side and shows the number column. If it is 300px or more, the number column is hidden. If it is narrower, the card is stacked vertically.
import { useWidthClass, type Breakpoints } from './useWidthClass';
// Keep the array outside the component so it is not recreated on each render
const CARD_BREAKPOINTS: Breakpoints<'wide' | 'medium' | 'narrow'> = [
[480, 'wide'],
[300, 'medium'],
[0, 'narrow'],
];
export function ProfileCard() {
const [ref, layout] = useWidthClass<HTMLDivElement, 'wide' | 'medium' | 'narrow'>(CARD_BREAKPOINTS);
return (
<div ref={ref}>
{/* Do not draw until the width is known */}
{layout && (
<div className={`card ${layout}`} data-layout={layout}>
<div className="avatar" />
<div>
<strong>ねこ</strong>
<p style={{ margin: 0, fontSize: 14 }}>レイアウト:{layout}</p>
</div>
{layout !== 'medium' && (
<div className="stats">
<span>記事 12</span>
<span>いいね 34</span>
</div>
)}
</div>
)}
</div>
);
}
The arrangement is changed by CSS applied to classes such as .card.wide. The number of grid columns changes, and in medium the number column is hidden.
.card { display: grid; gap: 12px; padding: 16px; border: 2px solid #00c8e8; border-radius: 10px; background: #eefafd; }
.card.narrow { grid-template-columns: 1fr; text-align: center; }
.card.medium { grid-template-columns: 64px 1fr; align-items: center; }
.card.wide { grid-template-columns: 96px 1fr 160px; align-items: center; }
.card.medium .stats { display: none; }

These are the layout names read after changing the width of the frame that contains the card.
枠の幅 480px: {"label":"カードの幅:480px","layout":"wide"}
枠の幅 479px: {"label":"カードの幅:479px","layout":"medium"}
枠の幅 300px: {"label":"カードの幅:300px","layout":"medium"}
枠の幅 299px: {"label":"カードの幅:299px","layout":"narrow"}
At the exact breakpoint values (480px and 300px), the wider name was chosen. I did not change the size of the screen (the browser window). The display changed only because of the width of the frame.
Putting a name in state, not the numeric width
If you put the numeric width in state, the component re-renders every time the width changes. I placed a component that computes the layout from the numeric width during rendering next to a component that uses useWidthClass to hold the name in state. I changed the frame width from 305px to 700px in steps of 5px, 80 times, and counted the renders. The frame width was changed directly in the DOM, not through React.
幅を変える前: {"byWidth":3,"byClass":3,"roCallbacks":4}
305px から 700px まで 5px ずつ 80 回変えたあと: {"byWidth":83,"byClass":5,"roCallbacks":164}
The component that stored the width in state (byWidth) rendered 80 more times. The component that stored the name in state (byClass) increased by only 2. During this period, the layout changed only once, when the width reached 480px and changed from medium to wide. As described in the official note on set-function caveats, if the new value is the same as the current value (compared with Object.is), React skips re-rendering. However, the same note says that React may still call the component before skipping the rendering of its children. This is likely why the count increased by 2 even though the layout changed only once.
Define the breakpoint array outside the component. If you write it inside, like useWidthClass([[400, 'wide'], [0, 'narrow']]), a new array is created on every render, and useCallback returns a new function. As described in the official caveats on ref callbacks, when a different function is passed to ref, React calls the cleanup of the previous function and then calls the new one. In my test, I re-rendered three times with a button, and observe went from 2 to 5. The observer was recreated each time.
マウント直後: {"created":2,"observe":2,"disconnect":1,"active":1,"callbacks":2}
+1 を3回押したあと: {"created":5,"observe":5,"disconnect":4,"active":1,"callbacks":5}
This screen does not use StrictMode, but observe is already called twice right after mounting. This is because monitoring started during the first render, and then the array was recreated when the re-render happened after the name was determined, which recreated the observer.
Pass the ref as a function, not with useRef
You can also receive the element with useRef and call observe inside useEffect. However, if the dependency array is empty, monitoring does not start when the element appears later. I compared the two approaches on a screen where a panel appears when a button is pressed.
パネルを出したあと: {"obj":"null","cb":"240","ro":{"created":2,"observe":2,"disconnect":1,"active":1,"callbacks":1}}
callback ref の側のパネルを消したあと: {"created":2,"observe":2,"disconnect":2,"active":0,"callbacks":1}
With the useRef and useEffect approach (obj), the element did not exist yet when the component mounted, so the width stayed null even after the panel appeared. With the ref callback approach (cb), monitoring started when the panel appeared, and it received a width of 240. When the panel was removed, disconnect was called, and the number of active observers returned to 0.
This screen was run with StrictMode. The extra single observe and disconnect come from the register-and-cleanup pair that the official caveats describe. In development builds with StrictMode, React performs this pair one extra time. Because the cleanup calls disconnect, no observer was left behind.
Which box does the width refer to?
I observed an element with a width of 300px, padding of 20px, border of 2px, and box-sizing: border-box, and compared the values. The second element had transform: scale(0.5) applied.
plain: {"id":"plain","contentRect":256,"contentBoxSize":256,"borderBoxSize":300,"offsetWidth":300,"getBoundingClientRect":300}
scaled: {"id":"scaled","contentRect":256,"contentBoxSize":256,"borderBoxSize":300,"offsetWidth":300,"getBoundingClientRect":150}
contentBoxSize was 256, which excludes padding and border. If you want to use a breakpoint that includes padding and border, use borderBoxSize. contentRect is also 256, but the MDN page on contentRect describes it as an older property left over from earlier implementations.
For the element shrunk with transform, getBoundingClientRect() returned 150, which matches what is visible. However, the ResizeObserver values remained 300 and 256, the sizes before shrinking. ResizeObserver gives you the size determined by layout, before transform is applied, not the visual size after transform shrinks it.
Right after observe is called, one notification is delivered. In my test, an element with a width of 200px delivered 200, and an element with display: none delivered 0. A hidden element has a width of 0, so this hook assigns it the narrowest name. When I removed display: none, a notification of 150 was delivered.
Do not observe an element whose width changes with its own contents
If the width of the observed element depends on the content you switch, and switching the content causes the width to return to the other side of the breakpoint, the switching never stops. I made a screen where an display: inline-block element is observed. When the width is 200px or more, it shows a short display 120px wide, and when it is less than 200px, it shows a long display 260px wide. I waited one second. The following shows the result when I called setState normally inside the callback.
開いた直後: {"renders":5,"callbacks":4}
1秒後: {"renders":65,"callbacks":64,"errors":0}
The following shows the result when I wrapped setState with flushSync.
開いた直後: {"renders":4,"callbacks":3}
1秒後: {"renders":64,"callbacks":63,"errors":63,"firstError":"ResizeObserver loop completed with undelivered notifications."}
With a normal setState, no error appeared, but the component re-rendered 60 times in one second, and the display kept flip-flopping. When I used flushSync inside the callback to force synchronous rendering, the display flip-flopped in the same way, and the error "ResizeObserver loop completed with undelivered notifications." was reported to window 63 times.
According to the MDN page on ResizeObserver, in the section on the notification error, the browser delivers notifications before painting the screen. If a size changes at that point, the browser recalculates styles and layout, which may produce further notifications. In this loop, the browser handles only notifications for elements deeper in the DOM than in the previous pass, immediately. Notifications for elements that are not deeper than in the previous pass are deferred to the next frame, and this error is reported. The same page also says that this mechanism only prevents the browser from freezing and does not stop the loop itself. Even with a normal setState, where no error appeared, the flip-flopping did not stop.
Watch the outer frame and switch by name
Observe the outer element whose width is determined by the parent. Changing the contents does not change that element's width. Call observe inside the ref callback and return a disconnect cleanup, and define the breakpoint array outside the component. If you put a name in state, React skips re-rendering as long as the value stays within the same breakpoint.





