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
- Initializing State:
const [isMobile, setIsMobile] = useState(undefined);
This state variable stores whether the user is on a mobile device or not.
- 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
).
- Listening for Changes:
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
This function updates the state when the screen size changes.
- 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!
Top comments (0)