Skip to content

Instantly share code, notes, and snippets.

@guillermodlpa
Created December 23, 2022 11:41
Show Gist options
  • Save guillermodlpa/a430b9d405eded7665abb00a7e785e2f to your computer and use it in GitHub Desktop.
Save guillermodlpa/a430b9d405eded7665abb00a7e785e2f to your computer and use it in GitHub Desktop.
Reusable hook to observe a node and run a throttled callback when its dimensions change
import throttle from 'lodash.throttle';
import React, { useEffect } from 'react';
/**
* Reusable hook to observe a node and run a throttled callback when its dimensions change
* Example usage can be to change the text within a flex grow container between
* a short and a long version depending on available space
*/
export default function useThrottledResizeObserver<T extends HTMLElement>(
ref: React.MutableRefObject<T>,
callback: (entries: ResizeObserverEntry[]) => void,
wait: number,
): void {
useEffect(() => {
if (!ref.current) {
return;
}
const throttledCallback = throttle(entries => {
callback(entries);
}, wait);
const observer = new ResizeObserver(throttledCallback);
observer.observe(ref.current);
return function cleanUp() {
throttledCallback.cancel();
observer.disconnect();
};
}, [ref, wait]); // eslint-disable-line react-hooks/exhaustive-deps
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment