In today’s multi-device world, providing an optimized user experience across mobile, tablet, and desktop is crucial. While CSS media queries handle much of responsive design, sometimes you need to trigger specific ReactJS component behavior or render different elements based on the device.
That’s where a custom React hook for device detection comes in handy!
Why a hook?
Hooks allow us to encapsulate reusable, stateful logic. By creating a useIsMobile hook, we can detect device type at runtime and have our components react dynamically, ensuring a truly adaptive experience.
Here’s a simple, robust useIsMobile hook you can use:
// File: js/hooks/useIsMobile.jsx
import { useState, useEffect } from 'react';
const useIsMobile = (breakpoint = 768) => {
const [isMobile, setIsMobile] = useState(window.innerWidth < breakpoint);
useEffect(() => {
const handleResize = () => {
setIsMobile(window.innerWidth < breakpoint);
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [breakpoint]); // Re-run effect if breakpoint changes
return isMobile;
};
export default useIsMobile;
How to use it in your components:
// File: js/MyResponsiveComponent.jsx
import React from 'react';
import { useIsMobile } from './hooks/useIsMobile'; // Adjust path as needed
function MyResponsiveComponent() {
const isMobile = useIsMobile(768); // Adjust a value as needed
return (
<div>
{isMobile ? (
<p>Welcome, mobile user! Here's your mobile-optimized content.</p>
) : (
<p>Hello desktop user! Enjoy the full experience.</p>
)}
{/* Example: Conditionally render a mobile-only menu */}
{isMobile && <MobileMenu />}
{!isMobile && <DesktopNavbar />}
</div>
);
}
// Example MobileMenu and DesktopNavbar components
const MobileMenu = () => <nav className="mobile-menu">...</nav>;
const DesktopNavbar = () => <nav className="desktop-navbar">...</nav>;
export default MyResponsiveComponent;
Key Advantages:
Real-time Responsiveness: Updates isMobile state whenever the browser window is resized or orientation changes.
Reusable Logic: Encapsulate the detection logic into a clean, reusable hook.
SSR Friendly: Includes a check for the window to prevent errors during server-side rendering.
Customizable: Easily adjust the breakpoint to fit your specific design needs.
We hope this blog may be understandable and useful to you. You can email us at mage2developer@gmail.com if we missed anything or if you want to add any suggestions. We will respond to you as soon as possible. Happy to help 🙂

