Skip to content

Instantly share code, notes, and snippets.

@velotiotech
Created June 25, 2020 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velotiotech/4a26bd0a87c9506ecf82c0f19e2fab82 to your computer and use it in GitHub Desktop.
Save velotiotech/4a26bd0a87c9506ecf82c0f19e2fab82 to your computer and use it in GitHub Desktop.
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