use-mobile.tsx821 BView on GitHub import * as React from 'react';
const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
// Initialize with the correct value immediately to avoid re-render on mount
const [isMobile, setIsMobile] = React.useState<boolean>(() => {
// Check if we're in a browser environment
if (typeof window !== 'undefined') {
return window.innerWidth < MOBILE_BREAKPOINT;
}
return false;
});
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
// Handler for when the media query state changes
const onChange = () => {
setIsMobile(mql.matches);
};
// Add listener for future changes
mql.addEventListener('change', onChange);
return () => mql.removeEventListener('change', onChange);
}, []);
return isMobile;
}