Skip to content

Instantly share code, notes, and snippets.

@ironyee
Created March 25, 2022 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ironyee/e36f9e2f39b6653624f53d2edda3c019 to your computer and use it in GitHub Desktop.
Save ironyee/e36f9e2f39b6653624f53d2edda3c019 to your computer and use it in GitHub Desktop.
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