Skip to content

Instantly share code, notes, and snippets.

@honungsburk
Last active July 19, 2022 10:09
Show Gist options
  • Save honungsburk/a8078189b62765bf3d69e87c96347c07 to your computer and use it in GitHub Desktop.
Save honungsburk/a8078189b62765bf3d69e87c96347c07 to your computer and use it in GitHub Desktop.
Whenever the "lead" DOM element is resized the function triggers and you can resize the follower DOM elements
import { RefObject, useEffect } from "react";
/**
*
* @param resize the function that runs every time `lead` is resized
* @param leadRef the HTMLElement that we are tracking
*/
export default function useOnResize<A extends HTMLElement>(
leadRef: RefObject<A>,
resize: (lead: A) => void,
deps: any[]
): void {
useEffect(() => {
const lead = leadRef.current;
if (lead) {
resize(lead);
const observer = new ResizeObserver(() => resize(lead));
observer.observe(lead);
return () => observer.disconnect();
}
}, [leadRef, ...deps]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment