use-screen-size
Simple hook to get the screen size, with optional transformations
Demo
Current Screen Size
0
Width (px)
0
Height (px)
Resize your browser window to see the values update in real-time
"use client";
import { useScreenSize } from "@/hooks/use-screen-size";
import { useState } from "react";
const UseScreenSizeDemo: React.FC = () => {
const [transformTo, setTransformTo] = useState<"%" | "px">("px");
const screenSize = useScreenSize({ transformTo: transformTo });
return (
<div className="text-center space-y-4">
<div className="text-lg font-semibold text-foreground">
Current Screen Size
</div>
<div className="grid grid-cols-2 gap-4 max-w-xs mx-auto">
<div className="bg-muted/50 rounded-lg p-4">
<div className="text-2xl font-bold text-foreground">
{screenSize.width}
</div>
<div className="text-sm text-muted-foreground">Width ({transformTo === "%" ? "%" : "px"})</div>
</div>
<div className="bg-muted/50 rounded-lg p-4">
<div className="text-2xl font-bold text-foreground">
{screenSize.height}
</div>
<div className="text-sm text-muted-foreground">Height ({transformTo === "%" ? "%" : "px"})</div>
</div>
</div>
<button onClick={() => setTransformTo(transformTo === "%" ? "px" : "%")}>
Get {transformTo === "%" ? "px" : "%"} Size
</button>
<p className="text-sm text-muted-foreground">
Resize your browser window to see the values update in real-time
</p>
</div>
);
};
export { UseScreenSizeDemo };Installation
Copy and paste the following code into your project.
"use client";
import { useEffect, useMemo, useState } from "react";
interface ScreenSizeOptions {
transformTo: "%" | "px";
}
const useScreenSize = (options?: ScreenSizeOptions) => {
const [screenSize, setScreenSize] = useState({
width: typeof window !== "undefined" ? document.documentElement.clientWidth : 0,
height: typeof window !== "undefined" ? document.documentElement.clientHeight : 0,
});
const baseWindowSize = useMemo(()=>({
width: typeof window !== "undefined" ? window.outerWidth : 0,
height: typeof window !== "undefined" ? window.outerHeight : 0,
}), []);
useEffect(() => {
const handleResize = () =>
setScreenSize({
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
});
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
switch(options?.transformTo) {
case "%":
return {
width: Math.round(screenSize.width * 100 / baseWindowSize.width),
height: Math.round(screenSize.height * 100 / baseWindowSize.height),
};
case "px": default:
return screenSize;
}
};
export default useScreenSize;Usage
import { useScreenSize } from "@/hooks/use-screen-size";const size = useScreenSize(); // pixel by default
const size = useScreenSize({ transformTo: "%" }); // percentage size