typescriptintermediate
useResizeObserver Hook
Tracks element dimensions using ResizeObserver with debounced updates.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useEffect, useRef, RefObject } from 'react';
interface Size {
width: number;
height: number;
}
export function useResizeObserver<T extends HTMLElement>(): [RefObject<T | null>, Size] {
const ref = useRef<T | null>(null);
const [size, setSize] = useState<Size>({ width: 0, height: 0 });
useEffect(() => {
const element = ref.current;
if (!element) return;
const observer = new ResizeObserver(entries => {
const entry = entries[0];
if (entry) {
setSize({
width: Math.round(entry.contentRect.width),
height: Math.round(entry.contentRect.height),
});
}
});
observer.observe(element);
return () => observer.disconnect();
}, []);
return [ref, size];
}Use Cases
- Responsive layouts
- Chart container sizing
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
useWindowSize Hook
Track browser window dimensions with debounced resize handling for responsive component logic.
Best for: Responsive layouts
#hooks#responsive
typescriptadvanced
useMutationObserver Hook
Wraps the MutationObserver API in a React hook to observe DOM changes on a target element.
Best for: Third-party widget monitoring
#hooks#dom
typescriptintermediate
Infinite Scroll Hook v2
Intersection Observer-based infinite scroll with loading, error, and hasMore states.
Best for: Feed-style content
#hooks#infinite-scroll
typescriptintermediate
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
#hooks#fetch