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
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
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.