react-query
Version:
Hooks for managing, caching and syncing asynchronous and remote data in React
28 lines (24 loc) • 795 B
JavaScript
import React from 'react';
export default function useMediaQuery(query) {
// Keep track of the preference in state, start with the current match
const [isMatch, setIsMatch] = React.useState(() => {
if (typeof window !== 'undefined') {
return window.matchMedia(query).matches;
}
}); // Watch for changes
React.useEffect(() => {
if (typeof window !== 'undefined') {
// Create a matcher
const matcher = window.matchMedia(query); // Create our handler
const onChange = ({
matches
}) => setIsMatch(matches); // Listen for changes
matcher.addListener(onChange);
return () => {
// Stop listening for changes
matcher.removeListener(onChange);
};
}
}, [isMatch, query, setIsMatch]);
return isMatch;
}