Last active
April 4, 2024 07:00
-
-
Save blift/bcb8461eb87cb068d8c4997b1316045d to your computer and use it in GitHub Desktop.
use min-width hook alternative for resize calculation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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