Skip to content

Instantly share code, notes, and snippets.

@cyclopslabs
Created December 14, 2022 02:36
Show Gist options
  • Save cyclopslabs/eb82b47b99b8d71f82a18a7d4ee93a42 to your computer and use it in GitHub Desktop.
Save cyclopslabs/eb82b47b99b8d71f82a18a7d4ee93a42 to your computer and use it in GitHub Desktop.
import { useRef, useEffect } from 'react';
// The type of the size object that will be passed to the callback
type Size = {
height: number;
width: number;
};
// The type of the callback that will be passed to the hook
type ResizeCallback = (size: Size) => void;
// The type of the ref that will be passed to the hook
type Ref = React.MutableRefObject<Element | null>;
const useResize = (ref: Ref, callback: ResizeCallback) => {
// Create a new ResizeObserver
const observer = useRef(new ResizeObserver((entries) => {
// Get the first and only entry in the ResizeObserver's list of entries
const entry = entries[0];
// Extract the height and width from the entry and pass them to the callback
const { height, width } = entry.contentRect;
callback({ height, width });
}));
useEffect(() => {
// Get the current value of the ref and cast it to an Element
const element = ref.current as Element;
// If the ref is not null, observe the element using the ResizeObserver
if (element) {
observer.current.observe(element);
}
// Return a cleanup function that will unobserve the element when the hook is
// unmounted
return () => observer.current.unobserve(element);
}, [ref]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment