Created
August 18, 2020 12:55
-
-
Save YoranBrondsema/156c9bd9a45d6d70a90af1dcdd42dc53 to your computer and use it in GitHub Desktop.
useOnElementResize hook for React.js
This file contains 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 { useEffect, useRef, useCallback } from 'react'; | |
export default function useOnElementResize(didResize) { | |
const ro = useRef(null); | |
const ref = useCallback( | |
(element) => { | |
if (element) { | |
if (ro.current) { | |
ro.current.disconnect(); | |
} | |
ro.current = new window.ResizeObserver((entries, observer) => { | |
didResize(element); | |
}); | |
ro.current.observe(element); | |
} | |
}, | |
[didResize] | |
); | |
useEffect( | |
() => { | |
return () => { | |
ro.current.disconnect(); | |
}; | |
}, | |
[] | |
); | |
return ref; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment