UNPKG

codedsaif-react-hooks

Version:

To make it easy for you to get started with GitLab, here's a list of recommended next steps.

32 lines (29 loc) 982 B
import { useState, useEffect } from "react"; /** * Custom hook to get the current window dimensions. * @returns {{ width: number, height: number }} - The current width and height of the window. * @example * function ResponsiveComponent() { * const { width } = useWindowSize(); * return ( * <div> * {width > 1024 ? ( * <h1>Desktop View 🖥️</h1> * ) : width > 768 ? ( * <h1>Tablet View 📱</h1> * ) : ( * <h1>Mobile View 📲</h1> * )} * </div> * ); */ function useWindowSize() { const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight }); useEffect(() => { const handleResize = () => setSize({ width: window.innerWidth, height: window.innerHeight }); window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []); return size; } export default useWindowSize;