Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Last active November 21, 2023 13:20
Show Gist options
  • Save smitroshin/d509c6a7de15c567722d4ad55a6fcb81 to your computer and use it in GitHub Desktop.
Save smitroshin/d509c6a7de15c567722d4ad55a6fcb81 to your computer and use it in GitHub Desktop.
React hook - useDebouncedWindowResize
import { useState } from "react";
import { useMount, usePrevious, useToggle } from "react-use";
export function debounce(func: Function, timeout = 300) {
let timer: any;
return (...args: any[]) => {
clearTimeout(timer);
timer = setTimeout(() => {
func(...args);
}, timeout);
};
}
/**
* Unit: ms
*/
const WINDOW_RESIZE_DEBOUNCE_TIME = 1000;
export const useDebouncedWindowResize = (debounceTime: number = WINDOW_RESIZE_DEBOUNCE_TIME) => {
const [size, setSize] = useState<{ width: number; height: number }>({
width: window.innerWidth,
height: window.innerHeight,
});
const [resizeTrigger, toggleResize] = useToggle(false);
const prevResizeTrigger = usePrevious(resizeTrigger);
const resized = resizeTrigger !== prevResizeTrigger && prevResizeTrigger !== undefined;
useMount(() => {
function handleWindowResize() {
setSize({
width: window.innerWidth,
height: window.innerHeight,
});
toggleResize();
}
const handleDebouncedWindowResize = debounce(handleWindowResize, debounceTime);
window.addEventListener("resize", handleDebouncedWindowResize);
return () => {
window.removeEventListener("resize", handleDebouncedWindowResize);
};
});
return {
...size,
resized,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment