Skip to content

Instantly share code, notes, and snippets.

@wolfcoder
Created October 22, 2024 07:49
Show Gist options
  • Save wolfcoder/1192bf99d69ae5a60e1a07112ef0c984 to your computer and use it in GitHub Desktop.
Save wolfcoder/1192bf99d69ae5a60e1a07112ef0c984 to your computer and use it in GitHub Desktop.
React hook device detection
import { useState, useEffect } from 'react';
const useDeviceDetection = () => {
const [device, setDevice] = useState('');
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;
};
export default useDeviceDetection;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment