Random UI

use-detect-device

Hook to detect the current device

Demo

Current Device

Desktop

Open on other devices to see different values

Installation

Copy and paste the following code into your project.

use-detect-device.ts
"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();