useIsTouchDevice
React hook to detect if the user's device is a touch device.
Add the hook via the CLI:
sh
npx @novajslabs/cli add useIsTouchDevice
sh
npx @novajslabs/cli add useIsTouchDevice
sh
pnpm dlx @novajslabs/cli add useIsTouchDevice
Or copy and paste the code into your project:
ts
import { useEffect, useState } from "react";
export function useIsTouchDevice() {
const [isTouchDevice, setIsTouchDevice] = useState(false);
useEffect(() => {
function onResize() {
setIsTouchDevice(
"ontouchstart" in window ||
navigator.maxTouchPoints > 0 ||
navigator.maxTouchPoints > 0
);
}
window.addEventListener("resize", onResize);
onResize();
return () => {
window.removeEventListener("resize", onResize);
};
}, []);
return isTouchDevice;
}
js
import { useEffect, useState } from "react";
export function useIsTouchDevice() {
const [isTouchDevice, setIsTouchDevice] = useState(false);
useEffect(() => {
function onResize() {
setIsTouchDevice(
"ontouchstart" in window ||
navigator.maxTouchPoints > 0 ||
navigator.maxTouchPoints > 0
);
}
window.addEventListener("resize", onResize);
onResize();
return () => {
window.removeEventListener("resize", onResize);
};
}, []);
return isTouchDevice;
}
Requirements
React 16.8 or higher
Return values
isTouchDevice
Type: boolean
Represents whether the user's device is a touch device (true
) or not (false
).
Example
tsx
import { useIsTouchDevice } from "./hooks/useIsTouchDevice";
function App() {
const isTouchDevice = useIsTouchDevice();
return (
<div>
<p>
{isTouchDevice ? "It is a touch device" : "It is not a touch device"}
</p>
</div>
);
}
export default App;
Use cases
Here are some use cases where this React hook is useful:
- Adapting gesture-based interactions for touch-enabled devices in a web-based drawing or painting tool
- Enhancing user experience by providing touch-specific navigation controls in a mobile-friendly website