Created
March 25, 2022 08:26
-
-
Save ironyee/e36f9e2f39b6653624f53d2edda3c019 to your computer and use it in GitHub Desktop.
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 { useCallback, useEffect, useRef, useState } from 'react'; | |
function debounce(callback: Function, delay = 300) { | |
let handle: number; | |
return function () { | |
if (handle) clearTimeout(handle); | |
handle = setTimeout(callback, delay); | |
}; | |
} | |
interface Size { | |
width: number; | |
height: number; | |
} | |
function useDomSize(onResize: (width: number, height: number) => void) { | |
const ref = useRef<HTMLDivElement>(null); | |
const size = useRef<Size | undefined>(undefined); | |
const update = useCallback(() => { | |
const target = ref.current; | |
if (!target || !size.current) { | |
return; | |
} | |
const { width, height } = size.current; | |
if (width === target.clientWidth && height === target.clientHeight) { | |
return; | |
} | |
size.current = { | |
width: target.clientWidth, | |
height: target.clientHeight, | |
}; | |
onResize(target.clientWidth, target.clientHeight); | |
}, [onResize]); | |
useEffect(() => { | |
update(); | |
const handler = debounce(update); | |
window.addEventListener('resize', handler); | |
return () => window.removeEventListener('resize', handler); | |
}, [update]); | |
return ref; | |
} | |
export default useDomSize; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment