useIsTouchDevice

React hook to detect if the user's device is a touch device.

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
}

React 16.8 or higher

  • Name
    isTouchDevice
    Type
    boolean
    Description

    Represents whether the user's device is a touch device (true) or not (false).

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

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