Last active
November 21, 2023 13:20
-
-
Save smitroshin/d509c6a7de15c567722d4ad55a6fcb81 to your computer and use it in GitHub Desktop.
React hook - useDebouncedWindowResize
This file contains 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 } 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