Open Hooks

useMobile

Detect if the current screen size matches a mobile breakpoint.

useMobile

A simple React hook that detects whether the current screen is considered "mobile" based on a specified breakpoint width.


📦 Installation

No external dependency needed

🧠 Purpose

useMobile helps you adapt your UI for smaller screens by returning a boolean based on the window width.


💡 Use Cases

  • Conditionally render mobile-friendly layouts
  • Disable/enable features on mobile
  • Toggle navigation styles

📁 Hook Code

useMobile.ts
import { useEffect, useState } from "react";

export function useMobile(breakpoint: number = 768): boolean {
  const [isMobile, setIsMobile] = useState(
    typeof window !== "undefined" ? window.innerWidth < breakpoint : false
  );

  useEffect(() => {
    function handleResize() {
      setIsMobile(window.innerWidth < breakpoint);
    }

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [breakpoint]);

  return isMobile;
}
useMobile.js
import { useEffect, useState } from "react";

export function useMobile(breakpoint = 768) {
  const [isMobile, setIsMobile] = useState(
    typeof window !== "undefined" ? window.innerWidth < breakpoint : false
  );

  useEffect(() => {
    function handleResize() {
      setIsMobile(window.innerWidth < breakpoint);
    }

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [breakpoint]);

  return isMobile;
}

🧪 Example

import { useMobile } from "@/hooks/useMobile";

export default function ResponsiveMessage() {
  const isMobile = useMobile();

  return <p>{isMobile ? "Mobile View Active" : "Desktop View Active"}</p>;
}

🧩 Hook Signature

function useMobile(breakpoint?: number): boolean;

📝 Parameters

PropTypeDefault
breakpoint?
number
768

🎯 Returns

PropTypeDefault
isMobile
boolean
-

🧯 Visual Behavior

Resize Behavior

The hook listens for window resize events and updates its value accordingly.


🏁 Summary

  • ✅ Detects mobile screens
  • ✅ Fully customizable breakpoint
  • ✅ React-only, no dependencies

🙋 Contribution

Found a bug or improvement? Submit a PR on GitHub