In this post, I’ll share a custom React hook called useResizeObserver
. This hook helps you observe and get the bounding client rect of a DOM element, updating the rect whenever the element is resized. It’s part of my React library, react-helper-hooks
, which contains many useful hooks to save developers time.
Source Code
import { useEffect, useRef, useState } from 'react'; type ObserverRect = Omit<DOMRectReadOnly, 'toJSON'>; export default function useResizeObserver(): Array<any> { const ref = useRef<any>(null); const [rect, setRect] = useState<ObserverRect>(); useEffect(() => { const observer = new ResizeObserver(() => { if (ref.current) { const boundingRect = ref.current.getBoundingClientRect(); setRect(boundingRect); } }); observer.observe(ref.current); return () => observer.disconnect(); }, [ref]); return [ref, rect];
}
How It Works
The useResizeObserver
hook leverages the ResizeObserver
API to track size changes of a DOM element. It returns a ref to be attached to the target element and the current bounding client rect of that element.
Example Usage
Here’s an example of how to use the useResizeObserver
hook in a functional component:
import React from 'react';
import useResizeObserver from './useResizeObserver'; function ExampleComponent() { const [ref, rect] = useResizeObserver(); return ( <> <textarea ref={ref} style={{ resize: 'both', height: 100, width: 300 }}> Resize this element to see the changes: </textarea> {rect && ( <div> <p>Top: {rect.top}</p> <p>Left: {rect.left}</p> <p>Width: {rect.width}</p> <p>Height: {rect.height}</p> </div> )} </> );
} export default ExampleComponent;
In this example, a textarea
element is made resizable. The useResizeObserver
hook tracks its dimensions, which are displayed outside the textarea
.
About react-helper-hooks
The useResizeObserver
hook is part of my React library, react-helper-hooks. This library includes a collection of custom hooks designed to save developers time and effort. Hooks like useResizeObserver
provide reusable, efficient solutions for common tasks in React applications.
Feel free to check out the library and contribute or suggest new hooks!
Let me know if you need any changes or additional information!
Follow me on X ( Twitter ) – https://twitter.com/punitsonime
Let’s connect on linked in – https://www.linkedin.com/in/punitsonime/
Discover more from Coursity
Subscribe to get the latest posts sent to your email.