Skip to content
60fps/ui

ResizeObserver

getResizeObserver() hands out a single shared ResizeObserver whose callbacks are coalesced into one requestAnimationFrame per element per frame. Many components can observe many elements without duplicate work or resize-loop thrash. useResizeObserver wraps it with framework lifecycle so you just pass a ref and a callback.

0 × 0

Drag the bottom-right corner to resize ↘

0 × 0

Drag the bottom-right corner to resize ↘

Usage

import { useRef, useState } from 'react';
import { useResizeObserver } from '@60fps/react/resize-observer';

function Measured() {
	const ref = useRef<HTMLDivElement>(null);
	const [width, setWidth] = useState(0);

	useResizeObserver(ref, (entry) => setWidth(entry.contentRect.width));

	return (
		<div ref={ref} className="resize overflow-auto">
			{Math.round(width)}px
		</div>
	);
}
<script setup lang="ts">
import { ref } from 'vue';
import { useResizeObserver } from '@60fps/vue/resize-observer';

const box = ref<HTMLElement | null>(null);
const width = ref(0);

useResizeObserver(box, (entry) => (width.value = entry.contentRect.width));
</script>

<template>
	<div ref="box" class="resize overflow-auto">{{ Math.round(width) }}px</div>
</template>

API

useResizeObserver(ref, callback)

Argument Type Default Description
ref RefObject<Element> | Ref<Element> The element to observe. Re-subscribes if it changes.
callback (entry, observer) => void Called once per frame with the latest ResizeObserverEntry for the element.

getResizeObserver(polyfill?, options?)

The framework-agnostic manager underneath the hooks.

Member Type Default Description
subscribe(el, cb) (Element, cb) => void Start observing an element; multiple callbacks per element are supported.
unsubscribe(el, cb) (Element, cb) => void Remove one callback; the element is unobserved once its last callback is gone.
observer ResizeObserver The underlying shared observer instance.
options.box 'content-box' | 'border-box' 'content-box' Which box metrics to observe. One shared observer is kept per box mode.