Skip to content

Instantly share code, notes, and snippets.

@blift
Last active April 4, 2024 07:00
Show Gist options
  • Save blift/bcb8461eb87cb068d8c4997b1316045d to your computer and use it in GitHub Desktop.
Save blift/bcb8461eb87cb068d8c4997b1316045d to your computer and use it in GitHub Desktop.
use min-width hook alternative for resize calculation
/**
* Use:
* const isMobile = useMinWidth('700px');
*
*/
import { useState, useEffect } from 'react';
export function useMinWidth(_width: string): boolean {
if (!_width) return false;
const x = window.matchMedia(`(min-width: ${_width})`)
const [isMobile, setIsMobile] = useState(!x.matches)
useEffect(() => {
const handleChange = (e: MediaQueryListEvent) => {
setIsMobile(!e.matches);
}
x.addEventListener('change', handleChange);
return () => {
x.removeEventListener('change', handleChange);
}
}, [x])
return isMobile;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment