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>
Code Breakdown
State Initialization: const [isMobile, setIsMobile] = useState(undefined);
Initializes the state to undefined
.
window.matchMedia()
: const mql = window.matchMedia(
(max-width: ${MOBILE_BREAKPOINT - 1}px));
Creates a media query matching screens narrower than the breakpoint (default 768px).
Event Listener: mql.addEventListener("change", onChange);
Adds an event listener to detect screen size changes. The onChange
function directly updates isMobile
with mql.matches
.
Cleanup: return () => mql.removeEventListener("change", onChange);
Removes the listener when the component unmounts, preventing memory leaks.
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>
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!