Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cleaner Efficient Code with Hooks and Functional Programming - Fixing Wrapper Hell with hooks - component turned into a custom hook
import { useState, useEffect } from "react";
export default function(query) {
let [matches, setMatches] = useState(window.matchMedia(query).matches);
useEffect(() => {
let media = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
const listener = () => setMatches(media.matches);
media.addListener(listener);
return () => media.removeListener(listener);
}, [query, matches]);
return matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment