Skip to content

Instantly share code, notes, and snippets.

@httpJunkie
Last active August 14, 2020 13:16
Show Gist options
  • Save httpJunkie/78ddedbce9aecf9da4317a1cdb124e3b to your computer and use it in GitHub Desktop.
Save httpJunkie/78ddedbce9aecf9da4317a1cdb124e3b to your computer and use it in GitHub Desktop.
useWindowSizeWithDebounce
import { useEffect, useState } from 'react';
const debounce = (delay: number, fn: any) => {
let timerId: any;
return function (...args: any[]) {
if (timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(() => {
fn(...args);
timerId = null;
}, delay);
};
};
export const useWindowSize = (debounceTime?: number) => {
const isClient: boolean = typeof window === 'object';
const getSize = () => ({
width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined
});
const [windowSize, setWindowSize] = useState(getSize);
useEffect(() => {
if (!isClient) {
return;
}
const handleResize = () => {
setWindowSize(getSize());
};
let handleResizeFn = handleResize;
if (debounceTime) {
handleResizeFn = debounce(debounceTime, handleResize);
}
window.addEventListener('resize', handleResizeFn);
return () => window.removeEventListener('resize', handleResizeFn);
}, []);
return windowSize;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment