Cleaner Efficient Code with Hooks and Functional Programming - Fixing Wrapper Hell with hooks - component turned into a custom hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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