Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
AI & KI NachrichtenAI Restrictions at NYCPS and LAUSD Reverberate Nationwide(24.09.2026 um 01:16 Uhr)
AI & KI NachrichtenMeta Connect 2026: The biggest news and announcements(24.09.2026 um 00:45 Uhr)
AI & KI NachrichtenMeta ditches the camera on its newest smart glasses(24.09.2026 um 01:37 Uhr)
AI & KI NachrichtenMuse is coming to Meta smart glasses(24.09.2026 um 01:40 Uhr)
AI & KI NachrichtenAI Restrictions at NYCPS and LAUSD Reverberate Nationwide(24.09.2026 um 01:16 Uhr)
AI & KI NachrichtenMeta Connect 2026: The biggest news and announcements(24.09.2026 um 00:45 Uhr)
AI & KI NachrichtenMeta ditches the camera on its newest smart glasses(24.09.2026 um 01:37 Uhr)
AI & KI NachrichtenMuse is coming to Meta smart glasses(24.09.2026 um 01:40 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

Detecting Mobile Devices in React with a Custom Hook

Responsive web design is a crucial aspect of modern web development. Sometimes, you need to implement conditional logic in your React application based on whether the user is on a mobile device or not. Instead of relying on CSS media…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

Responsive web design is a crucial aspect of modern web development. Sometimes, you need to implement conditional logic in your React application based on whether the user is on a mobile device or not.



Instead of relying on CSS media queries alone, we can use JavaScript to detect screen width dynamically and update our application state accordingly. In this blog, we'll explore how to create a simple yet effective React hook, useIsMobile, to determine whether the user is on a mobile device.









Why Use JavaScript for Mobile Detection?



While CSS media queries are great for styling, they don't provide a way to conditionally render or execute JavaScript code based on screen size. A JavaScript-based approach is helpful when you need to:



✅ Show or hide UI elements dynamically (e.g., displaying a mobile menu).

✅ Optimize performance by preventing unnecessary rendering on smaller screens.

✅ Adjust application behavior based on screen size (e.g., disabling animations on mobile).







Creating the useIsMobile Hook



Here’s a simple React hook that detects if the user's screen width is below a given breakpoint:




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(window.innerWidth < MOBILE_BREAKPOINT);
};

mql.addEventListener("change", onChange);

setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);

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

return !!isMobile;
}












Breaking Down the Code




  1. Initializing State:




const [isMobile, setIsMobile] = useState(undefined);






This state variable stores whether the user is on a mobile device or not.




  1. Using window.matchMedia():




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






We define a media query that matches screens smaller than the specified breakpoint (default is 768px).




  1. Listening for Changes:




const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};






This function updates the state when the screen size changes.




  1. Adding and Removing Event Listeners:




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







  • We listen for changes in screen size and update the state accordingly.

  • The event listener is removed when the component unmounts to prevent memory leaks.

  • Returning the Boolean Value:




return !!isMobile;






We return a boolean value (true for mobile, false otherwise) to ensure predictable behavior.









Using the useIsMobile Hook in a Component



Now that we have the hook, let’s see how to use it in a React component:




import React from "react";
import { useIsMobile } from "./useIsMobile";

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

return (
<div>
{isMobile ? (
<p>You're on a mobile device 📱</p>
) : (
<p>You
're on a desktop 🖥️</p>
)}
</div>
);
}






This will display different messages based on whether the screen width is smaller or larger than the defined breakpoint.









Advantages of This Approach



✅ Lightweight and efficient – Uses window.matchMedia instead of continuously checking window.innerWidth.

✅ Reusable – Can be used across multiple components.

✅ Real-time updates – Automatically updates when the screen size changes.

✅ Customizable – The breakpoint can be adjusted as needed.









Conclusion



Detecting screen size in JavaScript is useful for implementing mobile-specific logic in React applications. The useIsMobile hook provides an elegant solution for determining whether the user is on a mobile device, making it easy to customize your UI dynamically.



What other scenarios have you encountered where detecting mobile screens was useful? Let me know in the comments!

CTI Threat Relationship Graph2 Knoten / 1 Relationen
CVE / Incident Software MITRE ATT&CK CWE Weakness IoC
IR-PLAYBOOK-VULN-REMEDIATION
MEDIUM
SOC Incident Playbook: Vulnerability Remediation & Verification
1-Click Detection Engineering: Sigma & YARA Rules
SOC Ready
title: Detect Exploitation - Detecting Mobile Devices in React with a Custom Hook
id: f7a1f316-c971-48e0-86e2-471007f1782d
status: experimental
description: Automatisch generierte SIEM-Erkennungsregel basierend auf CTI Intelligence
references:
  - https://tsecurity.de/
author: iShareStuff CTI Automated Detection Engine
date: 2026-09-24
logsource:
  category: network_connection
  product: any
detection:
  selection:
      CommandLine|contains:
        - 'exploit'
  condition: selection
falsepositives:
  - Legitime administrative Zugriffe oder Penetrationstests
level: high
tags:
  - attack.initial_access
rule CTI_Threat_Indicator {
    meta:
        author = "iShareStuff CTI Automated Detection Engine"
        date = "2026-09-24"
        description = "YARA Signature for "
    strings:
        $str = "Detecting Mobile Devices in Re" ascii wide
    condition:
        any of them
}
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Detecting Mobile Devices in React with a Custom Hook

Thematisch verwandte Begriffe: Detecting, Mobile, Devices, React · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-96676 | A vulnerability was identified in Fast FAC1900R 20190827_2.0.2. The impa…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel TTP ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick