javascript
60 lines · 8 steps
A resize-observing hook in React
A custom hook that measures a DOM element's size with ResizeObserver and reports changes efficiently.
Explained by
highlit
1import { useState, useRef, useCallback, useLayoutEffect } from "react";
2
3export function useResizeObserver({ debounce = 0 } = {}) {
4 const [size, setSize] = useState({ width: 0, height: 0 });
5 const elementRef = useRef(null);
6 const observerRef = useRef(null);
7 const frameRef = useRef(null);
8 const timeoutRef = useRef(null);
9
10 const handleResize = useCallback(
11 (entries) => {
12 const entry = entries[0];
13 if (!entry) return;
14
15 const { width, height } = entry.contentRect;
16
17 const commit = () => {
18 setSize((prev) =>
19 prev.width === width && prev.height === height ? prev : { width, height }
20 );
21 };
22
23 if (debounce > 0) {
24 clearTimeout(timeoutRef.current);
25 timeoutRef.current = setTimeout(commit, debounce);
26 } else {
27 cancelAnimationFrame(frameRef.current);
28 frameRef.current = requestAnimationFrame(commit);
29 }
30 },
31 [debounce]
32 );
33
34 const ref = useCallback(
35 (node) => {
36 if (observerRef.current) {
37 observerRef.current.disconnect();
38 observerRef.current = null;
39 }
40
41 elementRef.current = node;
42
43 if (node) {
44 observerRef.current = new ResizeObserver(handleResize);
45 observerRef.current.observe(node);
46 }
47 },
48 [handleResize]
49 );
50
51 useLayoutEffect(() => {
52 return () => {
53 observerRef.current?.disconnect();
54 cancelAnimationFrame(frameRef.current);
55 clearTimeout(timeoutRef.current);
56 };
57 }, []);
58
59 return { ref, ...size };
60}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A callback ref lets you attach and tear down observers exactly when a node mounts or unmounts.
- 2Coalescing updates with requestAnimationFrame or a debounce timer prevents resize storms from thrashing renders.
- 3Refs hold mutable observer and timer handles so cleanup can reliably release them without triggering re-renders.
Related explainers
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
javascript
class HistoryStack { constructor(initial = '', limit = 100) { this.past = []; this.present = initial;
Building an undo/redo history stack
undo-redo
state-management
debouncing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-resize-observing-hook-in-react-explained-javascript-b8e2/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.