A simple hook that check if the device has touch or not.
import { useState, useEffect } from 'react';
export const useIsTouchDevice = () => {
const [isTouchDevice, setIsTouchDevice] = useState(false);
useEffect(() => {
let hasTouchScreen = false;
if ('maxTouchPoints' in navigator) {
hasTouchScreen = navigator.maxTouchPoints > 0;
} else {
const mediaQueryList = window.matchMedia('(pointer:coarse)');
if (mediaQueryList && mediaQueryList.media === '(pointer:coarse)') {
hasTouchScreen = !!mediaQueryList.matches;
} else {
// Fall back to user agent
const UA = window.navigator.userAgent;
hasTouchScreen =
/(BlackBerry|webOS|iPhone|IEMobile)/i.test(UA) ||
/(Android|Windows Phone|iPad|iPod)/i.test(UA);
}
}
if (hasTouchScreen) {
setIsTouchDevice(true);
} else {
setIsTouchDevice(false);
}
}, []);
return isTouchDevice;
};