|Kit

useContainerQuery

Tracks whether a container element's width is below a threshold, updating live via ResizeObserver — the container-query counterpart to useMediaQuery.

useContainerQuery tracks whether a container element's width is below maxWidth, updating live as the element is resized. It's the container-query counterpart to useMediaQuery, for components that need to respond to their own allocated space rather than the browser viewport — embedded in a panel, a resizable pane, or anything narrower than the window. AppShell's mobile breakpoint works this way.

import { useContainerQuery } from '@42/ui-react';
import { useRef } from 'react';

const ref = useRef<HTMLDivElement>(null);
const isNarrow = useContainerQuery(ref, 768);

<div ref={ref}>{isNarrow ? 'Narrow' : 'Wide'}</div>;

SSR-safe via useSyncExternalStore: the hydration snapshot is always false, since a server can't know the container's real size — a real browser corrects it shortly after mount, as ResizeObserver fires once immediately upon observe() with the element's current size.

Usage

Drag the box below to resize it — the reported state tracks the container's own width, not the browser window's.

Drag the bottom-right corner to resize this box.

Wide (≥ 400px)

Code

const ref = useRef(null);const isNarrow = useContainerQuery(ref, 400);<div ref={ref}>{isNarrow ? 'Narrow (< 400px)' : 'Wide (≥ 400px)'}</div>

API

Prop

Type

Returns a booleantrue when the container's width is below maxWidth.

On this page