Created
December 23, 2022 11:41
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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