useResizeObserver
Runs a callback whenever an element is resized, using a ResizeObserver. It
hands you the raw
ResizeObserverEntry
and holds no state, so it never re-renders your component by itself. It is the
low-level building block for your own size-aware hooks.
When to use it
- Reading the entry directly (
borderBoxSize,devicePixelContentBoxSize, ...) instead of just a width and height. - Updating a canvas, chart or third-party widget imperatively on resize, without re-rendering React.
- Writing to a ref, a store or analytics rather than to component state.
- Building your own helpers on top.
Only need the size as state? Use useElementSize,
which is built for exactly that.
Demo
Edit the code below — the preview re-runs live. Drag the bottom-right corner of each box to resize it, toggle Observe to pause the observer, and open the Console tab to see each callback.
Loading demo…
Signature
interface UseResizeObserverOptions {
box?: ResizeObserverBoxOptions;
enabled?: boolean;
}
type ResizeObserverHandler = (
entry: ResizeObserverEntry,
observer: ResizeObserver
) => void;
function useResizeObserver<T extends Element = HTMLElement>(
callback: ResizeObserverHandler,
options?: UseResizeObserverOptions
): (element: T | null) => void;
| Argument / option | Type | Description |
|---|---|---|
callback | (entry: ResizeObserverEntry, observer: ResizeObserver) | Called on every resize, including once right after observing starts. The latest callback is always used. |
box | "content-box" | "border-box" | "device-pixel-content-box" | Which box to observe. Defaults to "content-box". |
enabled | boolean | Set to false to pause observing. Resumes (and reports the current size) when true again. Defaults to true. |
Returns: a callback ref to attach to the element. The type parameter T
is the element type, for example useResizeObserver<HTMLDivElement>(...).
Usage notes
refis a callback ref, so it works when the element mounts later, is rendered conditionally, or is swapped for another one. It has a stable identity across renders.- A
ResizeObserverreports once as soon as it starts observing, so the callback runs with the initial size after the element mounts. UnlikeuseElementSize, the callback is not deduplicated: it runs for every entry the browser delivers. - The callback can change on every render without re-observing the element,
so inline functions are fine. Changing
boxor togglingenabledre-observes. - The hook does nothing on the server, and wherever
ResizeObserveris unavailable (older browsers, some test environments) it never throws. - The observer is disconnected on unmount, when the element changes, when
boxchanges, and whenenabledbecomesfalse. device-pixel-content-boxis not supported by every browser. Checkentry.devicePixelContentBoxSizebefore using it and fall back tocontentBoxSize.- Updating state from the callback in a way that changes the observed
element's own size can create a loop. Browsers report this as a
ResizeObserver loopwarning. Keep the observed element's size independent of what you store. - To combine it with another ref, call both from a function ref:
ref={(el) => { ref(el); myRef.current = el; }}.
Examples
const ref = useResizeObserver<HTMLDivElement>((entry) => {
console.log("width", entry.contentRect.width);
});
return <div ref={ref} />;
// Keep a canvas sharp by reading device pixels, without re-rendering
const ref = useResizeObserver<HTMLCanvasElement>(
(entry) => {
const size = entry.devicePixelContentBoxSize?.[0];
if (!size) return;
entry.target.width = size.inlineSize;
entry.target.height = size.blockSize;
},
{ box: "device-pixel-content-box" }
);
// Compose your own helpers on top
const useWidth = (enabled = true) => {
const [width, setWidth] = useState(0);
const ref = useResizeObserver<HTMLElement>(
(entry) => setWidth(entry.contentRect.width),
{ enabled }
);
return { ref, width };
};
// Share the element with another ref
const sizeRef = useResizeObserver<HTMLDivElement>(onResize);
const containerRef = useRef<HTMLDivElement>(null);
return (
<div
ref={(el) => {
sizeRef(el);
containerRef.current = el;
}}
/>
);
Hook source
View useResizeObserver source
useResizeObserver sourceuse-resize-observer.ts
import { useEffect, useState } from "react";
import { useLatest } from "./use-latest";
/** Options for {@link useResizeObserver}. */
export interface UseResizeObserverOptions {
/**
* Which box to observe, passed straight to `ResizeObserver.observe`.
* Defaults to `"content-box"`. Use `"device-pixel-content-box"` for
* device-pixel measurements (for example to size a `<canvas>` crisply).
*/
box?: ResizeObserverBoxOptions;
/**
* Set to `false` to pause observing, for example while a panel is closed.
* Observing resumes (and reports the current size) when it is `true` again.
* Defaults to `true`.
*/
enabled?: boolean;
}
/**
* Called with the raw `ResizeObserverEntry` each time the observed element is
* resized, including once right after observing starts.
*/
export type ResizeObserverHandler = (
entry: ResizeObserverEntry,
observer: ResizeObserver
) => void;
/**
* Runs a callback whenever an element is resized, using a `ResizeObserver`.
* It is the low-level building block behind size-tracking hooks: it hands you
* the raw `ResizeObserverEntry` and holds no state, so it never re-renders your
* component on its own. Need the size as state? Use `useElementSize`.
*
* - **Usage:** attach the returned `ref` to any element. It is a callback ref,
* so it also works when the element mounts later, is rendered conditionally,
* or is swapped for another one.
* - **Raw entry:** the callback gets the `ResizeObserverEntry`, so you choose
* what to read (`contentRect`, `borderBoxSize`, `devicePixelContentBoxSize`,
* ...) and where to put it (state, a ref, a canvas, a store).
* - **Latest callback:** the callback may change on every render without
* re-observing the element.
* - **Options:** pick the observed `box`, or pause with `enabled: false`.
* - **SSR-safe:** does nothing on the server, and wherever `ResizeObserver` is
* unavailable.
* - **Cleanup:** the observer is disconnected on unmount, when the element
* changes, when `box` changes, and when `enabled` becomes `false`.
*
* A `ResizeObserver` reports once as soon as observing starts, so the callback
* runs with the initial size after the element mounts. To combine the `ref`
* with another ref, call both from a function ref, for example
* `ref={(el) => { ref(el); myRef.current = el; }}`.
*
* @typeParam T - The type of element being observed. Defaults to `HTMLElement`.
* @param callback - Called with the `ResizeObserverEntry` and the observer on every resize.
* @param options - Optional `box` and `enabled` settings.
* @returns A callback `ref` to attach to the element you want to observe.
*
* @example
* ```tsx
* const ref = useResizeObserver<HTMLDivElement>((entry) => {
* console.log("width", entry.contentRect.width);
* });
*
* return <div ref={ref} />;
* ```
*
* @example
* ```tsx
* // Keep a canvas sharp by reading device pixels, without re-rendering
* const ref = useResizeObserver<HTMLCanvasElement>(
* (entry) => {
* const size = entry.devicePixelContentBoxSize?.[0];
* if (!size) return;
* entry.target.width = size.inlineSize;
* entry.target.height = size.blockSize;
* },
* { box: "device-pixel-content-box" }
* );
* ```
*
* @example
* ```tsx
* // Compose your own helpers on top
* const useWidth = (enabled = true) => {
* const [width, setWidth] = useState(0);
* const ref = useResizeObserver<HTMLElement>(
* (entry) => setWidth(entry.contentRect.width),
* { enabled }
* );
* return { ref, width };
* };
* ```
*
* For a live, editable example, see the [useResizeObserver docs page](https://altalyst-solutions.github.io/hookify/hooks/use-resize-observer).
*
* @see [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver)
*/
export const useResizeObserver = <T extends Element = HTMLElement>(
callback: ResizeObserverHandler,
options?: UseResizeObserverOptions
): ((element: T | null) => void) => {
const box = options?.box ?? "content-box";
const enabled = options?.enabled ?? true;
const callbackRef = useLatest(callback);
const [element, setElement] = useState<T | null>(null);
useEffect(() => {
if (!enabled || !element || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver((entries, self) => {
for (const entry of entries) callbackRef.current(entry, self);
});
observer.observe(element, { box });
return () => observer.disconnect();
}, [element, box, enabled, callbackRef]);
return setElement;
};