Created
August 8, 2024 18:09
-
-
Save knownasilya/4662b205d23fba484a128716c22de5d0 to your computer and use it in GitHub Desktop.
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 {RefObject, useEffect, useRef} from 'react'; | |
export default function useElementResized<T extends HTMLElement>( | |
check: (entry: ResizeObserverEntry, element: T) => boolean, | |
callback: (element: T) => void, | |
ref?: RefObject<T> | |
) { | |
const backupRef = useRef<T>(null); | |
const actualRef = ref ?? backupRef; | |
useEffect(() => { | |
const resizeObserver = new ResizeObserver((entries) => { | |
if (!actualRef.current) { | |
return; | |
} | |
if (check(entries[0], actualRef.current)) { | |
callback(actualRef.current); | |
} | |
}); | |
if (actualRef.current && actualRef.current instanceof Element) { | |
resizeObserver.observe(actualRef.current); | |
} | |
return () => resizeObserver.disconnect(); | |
}, [actualRef.current]); | |
return actualRef; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment