qol-hooks
Version:
A collection of React hooks to improve the quality of life of developers.
37 lines (36 loc) • 984 B
JavaScript
import { useState, useEffect } from "react";
/**
* @description A hook to get the current window size
* @returns {WindowSize} The current window size
*
* @example ```tsx
* const { width, height } = useWindowSize();
* return (
* <p>
* Window width: {width}, window height: {height}
* </p>
* );
* ```
*/
function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
// Don't run this code on the server
if (typeof window === "undefined")
return;
function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
window.addEventListener("resize", handleResize);
handleResize();
return () => window.removeEventListener("resize", handleResize);
}, []);
return windowSize;
}
export default useWindowSize;