Created
October 6, 2021 02:32
-
-
Save dudo/7d0ec005407c099b07deaecd0593a050 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { 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