Everyone knows responsive design is crucial for a seamless user experience across devices. While CSS frameworks offer utility classes for screen sizes, detecting screen size programmatically can be useful sometimes. This is where the useScreenSize React hook comes in.
The "useScreenSize" hook allows you to dynamically detect the current screen size and respond to changes in real-time. This hook returns screen size values like "xs", "sm", "md", "lg", "xl", and "2xl", which correspond to the screen widths used in popular CSS frameworks such as Tailwind CSS.
1.Define the hook
1export const useScreenSize = () => {};
2.Managing State with useState
1import { useState } from "react";23export const useScreenSize = () => {4const [screenSize, setScreenSize] =5 (useState < "xs") | "sm" | "md" | "lg" | "xl" | "2xl" | ("" > "");6}
We use the useState hook to create a state variable screenSize that can take one of several string values representing different screen size categories: "xs", "sm", "md", "lg", "xl", and "2xl". The default value is an empty string (""), which will be updated once the screen size is determined.
3.Detecting Window Resize Events
1import { useState, useEffect } from "react";23 export const useScreenSize = () => {4 const [screenSize, setScreenSize] =5 (useState < "xs") | "sm" | "md" | "lg" | "xl" | "2xl" | ("" > "");67 useEffect(() => {8 const handleResize = () => {9 if (window.innerWidth < 640) {10 setScreenSize("xs");11 } else if (window.innerWidth >= 640 && window.innerWidth < 768) {12 setScreenSize("sm");13 } else if (window.innerWidth >= 768 && window.innerWidth < 1024) {14 setScreenSize("md");15 } else if (window.innerWidth >= 1024 && window.innerWidth < 1280) {16 setScreenSize("lg");17 } else if (window.innerWidth >= 1280 && window.innerWidth < 1536) {18 setScreenSize("xl");19 } else if (window.innerWidth >= 1536) {20 setScreenSize("2xl");21 }22 };2324 window.addEventListener("resize", handleResize);25 handleResize();2627 return () => window.removeEventListener("resize", handleResize);2829 }, []);30 }
useEffect - This ensures that the screen size is calculated after the component mounts, and it updates dynamically as the user resizes the window.
handleResize - Inside this function, we check the width of the browser window using window.innerWidth and set the screenSize accordingly: Below 640 pixels: "xs" 640–768 pixels: "sm" 768–1024 pixels: "md" 1024–1280 pixels: "lg" 1280–1536 pixels: "xl" Above 1536 pixels: "2xl"
Event Listener - We attach the resize event listener to trigger the "handleResize" function every time the window is resized. This ensures that "screenSize" stays up-to-date.
Cleanup - The return function within "useEffect" removes the resize event listener when the component unmounts, preventing potential memory leaks.
1import React from "react";2import useScreenSize from "./useScreenSize";34const MyResponsiveComponent = () => {5const screenSize = useScreenSize();67return (89<div>10<h1>Current screen size: {screenSize}</h1>11{screenSize === "xs" && <p>This is a mobile-sized screen!</p>}12{screenSize === "lg" && <p>You are viewing this on a large screen.</p>}13</div>14); };1516export default MyResponsiveComponent
In this example, the screen size is dynamically detected and displayed in the component. We also use the detected "screenSize" to conditionally render different content based on the user's device.
Reactivity - The hook automatically detects screen size changes and updates the UI in real-time.
Flexibility - By handling screen sizes programmatically, you can conditionally render different components or styles in your React app.
Customization - You can easily modify the breakpoints in the hook to match your specific design requirements.
Feel free to try out this hook in your projects! Let me know your thoughts, and happy coding!