Created
January 29, 2021 16:12
-
-
Save didacus/ae19f2e3fb6c5f0de61e3dc7314ad24f to your computer and use it in GitHub Desktop.
React hook to capture window size (Debounced).
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, useEffect } from "react" | |
// Debounce function | |
function debounce(func, wait, immediate) { | |
var timeout | |
return function () { | |
var context = this, | |
args = arguments | |
var later = function () { | |
timeout = null | |
if (!immediate) func.apply(context, args) | |
} | |
var callNow = immediate && !timeout | |
clearTimeout(timeout) | |
timeout = setTimeout(later, wait) | |
if (callNow) func.apply(context, args) | |
} | |
} | |
export default function useWindowSize() { | |
function getSize() { | |
return { | |
width: window.innerWidth, | |
height: window.innerHeight, | |
} | |
} | |
const [windowSize, setWindowSize] = useState(getSize) | |
useEffect(() => { | |
// Debounce to avoid the function fire multiple times | |
var handleResizeDebounced = debounce(function handleResize() { | |
setWindowSize(getSize()) | |
}, 250) | |
window.addEventListener("resize", handleResizeDebounced) | |
return () => window.removeEventListener("resize", handleResizeDebounced) | |
}, []) | |
return windowSize | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment