Skip to content

Instantly share code, notes, and snippets.

@velotiotech
Created June 25, 2020 12:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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