use-detect-device
Hook to detect the current device
Demo
Current Device
Desktop
Open on other devices to see different values
"use client";
import { useDevice } from "@/hooks/use-detect-device";
const UseDetectDeviceDemo: React.FC = () => {
const device = useDevice();
return (
<div className="text-center space-y-4">
<div className="text-sm text-muted-foreground">
Current Device
</div>
<p className="text-lg font-semibold text-foreground">
{device}
</p>
<p className="text-sm text-muted-foreground mt-8">
Open on other devices to see different values
</p>
</div>
);
}
export { UseDetectDeviceDemo };Installation
Copy and paste the following code into your project.
"use client";
import { useEffect, useState } from "react";
type Device = "Mobile" | "Tablet" | "Desktop";
/**
* Hook to detect the device type
* @returns {Device} The device type
*/
export const useDevice = (): Device => {
const [device, setDevice] = useState<Device>("Desktop");
useEffect(() => {
const handleDeviceDetection = () => {
const userAgent = navigator.userAgent.toLowerCase();
const isMobile =
/iphone|ipad|ipod|android|blackberry|windows phone/g.test(userAgent);
const isTablet =
/(ipad|tablet|playbook|silk)|(android(?!.*mobile))/g.test(userAgent);
if (isMobile) {
setDevice("Mobile");
} else if (isTablet) {
setDevice("Tablet");
} else {
setDevice("Desktop");
}
};
handleDeviceDetection();
window.addEventListener("resize", handleDeviceDetection);
return () => {
window.removeEventListener("resize", handleDeviceDetection);
};
}, []);
return device;
};Usage
import { useDevice } from "@/hooks/use-detect-device";const device = useDevice();