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

Walkthrough

Space play step click any line
Three takeaways
  1. 1A callback ref lets you attach and tear down observers exactly when a node mounts or unmounts.
  2. 2Coalescing updates with requestAnimationFrame or a debounce timer prevents resize storms from thrashing renders.
  3. 3Refs hold mutable observer and timer handles so cleanup can reliably release them without triggering re-renders.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A resize-observing hook in React — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code