useDetectDevice
A hook for detecting the user's device type and platform
Source Code
"use client";
import { useEffect, useState } from "react";
type useDetectDevidePorps = {
isMobile: boolean;
isDesktop: boolean;
isAndroid: boolean;
isIos: boolean;
};
const getDetectDevice = (
userAgent: NavigatorID["userAgent"]
): useDetectDevidePorps => {
const isAndroid = /Android/.test(userAgent);
const isIos = /iPad|iPhone/.test(userAgent);
const isMobile = isAndroid || isIos;
const isDesktop = !isMobile;
return {
isMobile,
isDesktop,
isAndroid,
isIos,
};
};
const useDetectDevice = () => {
const [deviceInfo, setDeviceInfo] = useState<useDetectDevidePorps>({
isMobile: false,
isDesktop: false,
isAndroid: false,
isIos: false,
});
useEffect(() => {
const userAgent =
typeof navigator === "undefined" ? "SSR" : navigator.userAgent;
setDeviceInfo(getDetectDevice(userAgent));
}, []);
return deviceInfo;
};
export default useDetectDevice;
Features
- Device Detection: Detect if the user is on a mobile or desktop device
- Platform Detection: Identify specific platforms (Android, iOS)
- SSR Support: Handles server-side rendering gracefully
API Reference
The hook returns an object with the following methods:
Prop | Default | Type | Description |
---|---|---|---|
| - |
| True if the device is a mobile device |
| - |
| True if the device is a desktop device |
| - |
| True if the device is running Android. |
| - |
| True if the device is running iOS (iPhone, iPad, or iPod). |
Examples
Basic Usage
const Example = () => {
const { isMobile } = useDetectDevice();
return <div>{isMobile ? <MobileLayout /> : <DesktopLayout />}</div>;
};
Platform-Specific Features
const AddToWallet = () => {
const { isAndroid, isIos } = useDetectDevice();
return (
<div>
{isAndroid && <AddToGoogleWallet />}
{isIos && <AddToAppleWallet />}
</div>
);
};
Technical Notes
- The hook uses the
navigator.userAgent
string to detect devices