use-mobile.tsx
Overview
The use-mobile.tsx file defines a custom React hook, useIsMobile, that provides a simple and reactive way to detect if the current viewport width corresponds to a mobile device screen size. It uses the browser's window.matchMedia API to listen for viewport width changes and updates its internal state accordingly.
This hook abstracts away the logic for responsive breakpoint detection, enabling React components to easily adapt their rendering or behavior when the user is on a mobile device (defined here as any screen width less than 768 pixels).
Detailed Explanation
Constants
MOBILE_BREAKPOINT:
const MOBILE_BREAKPOINT = 768;This constant defines the pixel width threshold separating mobile from non-mobile screen sizes. It is set to 768 pixels, a common breakpoint for responsive web design.
Function: useIsMobile
export function useIsMobile(): boolean
Purpose
useIsMobile is a custom React hook that returns a boolean indicating whether the current browser window width is less than the mobile breakpoint. It automatically updates its value when the viewport size changes.
Parameters
This hook does not take any parameters.
Returns
boolean:
Returnstrueif the viewport width is less than 768 pixels (i.e., mobile screen), otherwisefalse.
Usage Example
import React from 'react';
import { useIsMobile } from './use-mobile';
function ResponsiveComponent() {
const isMobile = useIsMobile();
return (
<div>
{isMobile ? (
<p>You are using a mobile device.</p>
) : (
<p>You are using a desktop or large screen device.</p>
)}
</div>
);
}
Implementation Details
State Initialization:
The hook usesReact.useStateto maintain theisMobileboolean state. Initially, it is set toundefinedto indicate that no measurement has been made yet.Effect Setup:
React.useEffectis used to set up a media query listener on component mount and clean it up on unmount.Media Query:
Thewindow.matchMediaAPI is used with the query(max-width: 767px)(which isMOBILE_BREAKPOINT - 1) to detect if the screen width is below the breakpoint.Event Listener:
An event listener is added to the media query list to listen for changes. Whenever the viewport crosses the breakpoint threshold, the listener callback updates theisMobilestate accordingly.Initial State Update:
The hook immediately sets the current state ofisMobilebased on the currentwindow.innerWidth.Cleanup:
The event listener is removed when the component using this hook unmounts, preventing memory leaks.
Browser Support Note
The addEventListener method on MediaQueryList is used here (instead of the deprecated addListener), which is supported in modern browsers. For older browsers, a fallback might be needed.
Interaction with Other Parts of the Application
This hook is designed to be imported and used by React components that require responsive behavior based on screen size.
It abstracts the screen size detection logic, allowing components to remain clean and focused on rendering.
It does not depend on or modify any global application state.
Can be combined with other hooks or context providers for richer responsive UI features.
Mermaid Component Diagram
componentDiagram
component useIsMobile {
+useState(isMobile: boolean | undefined)
+useEffect(() => {
-setup MediaQueryList for (max-width: 767px)
-addEventListener('change', onChange)
-set initial isMobile based on window.innerWidth
-cleanup listener on unmount
})
+returns boolean isMobile
}
component React {
+useState()
+useEffect()
}
React --> useIsMobile : uses hooks
Summary
File Purpose: Provides a React hook to detect mobile screen size responsively.
Key Export:
useIsMobilehook.Breakpoint Used: 768 pixels.
Core API:
window.matchMediawith event listeners.Benefits: Simplifies responsive design logic in React components.
Usage: Import and call
useIsMobilewithin functional React components to conditionally render or behave differently on mobile devices.
This file is a utility hook focused on responsive design detection, a common requirement in modern React applications for creating adaptive user interfaces.