tom/use-event-listener

This commit is contained in:
Tom Moor
2022-04-17 11:00:28 -07:00
parent e4e98286f4
commit 2fb0182e16
7 changed files with 99 additions and 68 deletions

View File

@@ -1,28 +1,35 @@
import { debounce } from "lodash";
import * as React from "react";
import useEventListener from "./useEventListener";
/**
* A debounced hook that listens to the window resize event and returns the
* size of the current window.
*
* @returns An object containing width and height of the current window
*/
export default function useWindowSize() {
const [windowSize, setWindowSize] = React.useState({
width: window.innerWidth,
height: window.innerHeight,
});
React.useEffect(() => {
// Handler to call on window resize
const handleResize = debounce(() => {
// Set window width/height to state
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}, 100);
const handleResize = React.useMemo(
() =>
debounce(() => {
// Set window width/height to state
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}, 100),
[]
);
// Add event listener
window.addEventListener("resize", handleResize);
useEventListener("resize", handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Call handler right away so state gets updated with initial window size
handleResize();
return () => window.removeEventListener("resize", handleResize);
}, []);
return windowSize;
}