Detecting and Adapting to Device Types in React with Custom Hooks

·

1 min read

  • In this blog post, we’ll explore a custom React hook that allows you to detect the device type and adapt your UI based on the screen width.

useDeviceType Hook

import { useState, useEffect } from 'react';


const useDeviceType = () => {
  const [deviceType, setDeviceType] = useState(null);

  // Define constants for media queries
  const MEDIA_QUERIES = {
    MOBILE: '(max-width: 767px)',
    TABLET: '(min-width: 768px) and (max-width: 1023px)',
    LAPTOP: '(min-width: 1024px) and (max-width: 1439px)',
    DESKTOP: '(min-width: 1440px)',
  };

  useEffect(() => {
    const mediaQuery = window.matchMedia(

[CLICK HERE TO READ MORE]