useIsMobile Hook

A custom React hook to detect mobile viewport based on a specified breakpoint.

import * as React from "react";

# useIsMobile Hook

This hook checks whether the viewport width is below the defined mobile breakpoint and returns a boolean indicating the state.

### Usage


import { useIsMobile } from "./useIsMobile";

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

  return (
    <div>
      {isMobile ? <p>You are on a mobile device</p> : <p>You are on a desktop device</p>}
    </div>
  );
}

Hook Implementation

import * as React from "react";

const MOBILE_BREAKPOINT = 768;

export function useIsMobile() {
  const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined);

  React.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);
  }, []);

  return !!isMobile;
}

Props

  • None.

Dependencies

  • react

On this page