Home > Web Front-end > JS Tutorial > Detecting Mobile Devices in React with a Custom Hook

Detecting Mobile Devices in React with a Custom Hook

Patricia Arquette
Release: 2025-01-29 14:30:09
Original
277 people have browsed it

Detecting Mobile Devices in React with a Custom Hook

Modern responsive web design often requires adapting React applications based on whether a user is on a mobile device. While CSS media queries handle styling, JavaScript offers dynamic screen width detection for conditional rendering and behavior adjustments. This article demonstrates a custom React hook, useIsMobile, for efficient mobile device detection.


Why JavaScript for Mobile Detection?

CSS media queries excel at styling, but lack the ability to conditionally execute JavaScript based on screen size. A JavaScript approach is crucial for:

✅ Dynamically showing/hiding UI elements (e.g., mobile menus). ✅ Optimizing performance by avoiding unnecessary rendering on smaller screens. ✅ Adapting application behavior to screen size (e.g., disabling animations on mobile).


Building the useIsMobile Hook

This React hook determines if the screen width is below a defined breakpoint:

<code class="language-javascript">import { useEffect, useState } from "react";

export function useIsMobile(MOBILE_BREAKPOINT = 768) {
  const [isMobile, setIsMobile] = useState(undefined);

  useEffect(() => {
    const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
    const onChange = () => setIsMobile(mql.matches);

    mql.addEventListener("change", onChange);
    return () => mql.removeEventListener("change", onChange);
  }, [MOBILE_BREAKPOINT]);

  return !!isMobile;
}</code>
Copy after login

Code Breakdown

  1. State Initialization: const [isMobile, setIsMobile] = useState(undefined); Initializes the state to undefined.

  2. window.matchMedia(): const mql = window.matchMedia((max-width: ${MOBILE_BREAKPOINT - 1}px)); Creates a media query matching screens narrower than the breakpoint (default 768px).

  3. Event Listener: mql.addEventListener("change", onChange); Adds an event listener to detect screen size changes. The onChange function directly updates isMobile with mql.matches.

  4. Cleanup: return () => mql.removeEventListener("change", onChange); Removes the listener when the component unmounts, preventing memory leaks.

  5. Boolean Return: return !!isMobile; Returns a boolean representing mobile status.


Using useIsMobile in a Component

Here's how to integrate the hook:

<code class="language-javascript">import React from "react";
import { useIsMobile } from "./useIsMobile";

export default function ResponsiveComponent() {
  const isMobile = useIsMobile();

  return (
    <div>
      {isMobile ? <p>Mobile Device ?</p> : <p>Desktop ?️</p>}
    </div>
  );
}</code>
Copy after login

This renders different messages based on the detected screen size.


Advantages

Lightweight and Efficient: Uses window.matchMedia for optimized performance. ✅ Reusable: Easily integrated across multiple components. ✅ Real-time Updates: Dynamically updates on screen size changes. ✅ Customizable: The breakpoint is configurable.


Conclusion

JavaScript-based screen size detection is valuable for creating truly responsive React applications. The useIsMobile hook provides a clean and efficient solution for mobile device detection, enabling dynamic UI adjustments.

The above is the detailed content of Detecting Mobile Devices in React with a Custom Hook. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template