useResizeObserver
Description
Use useResizeObserver
to observe the size of an element. The hook returns a ref that you need to attach to the element you want to observe. The callback function is called with the element and the ResizeObserverEntry
object.
Parameters
callback
(element: any, entry: ResizeObserverEntry) => void
The callback.
=>
react.RefObject<T | null>
The ref.
Example
Inspect
Source code
/packages/react-hooks/hooks/useResizeObserver.ts
import { useRef } from 'react';
import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect';
/**
* Use `useResizeObserver` to observe the size of an element. The hook returns a ref that you need to attach to the element you want to observe. The callback function is called with the element and the `ResizeObserverEntry` object.
* @param callback - The callback.
* @returns The ref.
* @public
*/
export function useResizeObserver<T extends Element = any>(callback: (element: any, entry: ResizeObserverEntry) => void) {
const ref = useRef<T>(null);
useIsomorphicLayoutEffect(() => {
const element = ref?.current;
if (!element) {
return undefined;
}
const sizeObserver = new ResizeObserver((entries) => {
callback(element, entries[0]);
});
sizeObserver.observe(element);
return () => {
sizeObserver.disconnect();
};
}, [callback, ref]);
return ref;
}
Last updated on