Skip to content

Instantly share code, notes, and snippets.

@dudo
Created October 6, 2021 02:32
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dudo/7d0ec005407c099b07deaecd0593a050 to your computer and use it in GitHub Desktop.
import { useState, useLayoutEffect } from "react";
export const useViewportSize = (debounceTime = 250) => {
const [viewportSize, setViewportSize] = useState({
width: undefined,
height: undefined
});
const debounce = (fn, ms) => {
let timer;
return () => {
if (timer !== null)
clearTimeout(timer);
timer = window.setTimeout(() => {
timer = null;
fn();
}, ms);
};
};
useLayoutEffect(() => {
const debouncedHandleResize = debounce(() => {
setViewportSize({
width: window.innerWidth,
height: window.innerHeight
});
}, debounceTime);
window.addEventListener("resize", debouncedHandleResize);
debouncedHandleResize();
return () => window.removeEventListener("resize", debouncedHandleResize);
});
return viewportSize;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment