@jk-core/hooks
Version:
hooks for jk
24 lines (18 loc) • 734 B
text/typescript
import { useEffect, useRef, useState } from 'react';
const useMediaQuery = (width:number) => {
const [matches, setMatches] = useState(() => window.matchMedia(`(max-width: ${width}px)`).matches);
const matchMediaRef = useRef<MediaQueryList | null>(null);
useEffect(() => {
const matchMedia = window.matchMedia(`(max-width: ${width}px)`);
matchMediaRef.current = matchMedia;
function handleChange() {
setMatches(window.matchMedia(`(max-width: ${width}px)`).matches);
}
matchMediaRef.current.addEventListener('change', handleChange);
return () => {
matchMediaRef.current?.removeEventListener('change', handleChange);
};
}, [width]);
return matches;
};
export default useMediaQuery;