Last active
March 19, 2019 01:17
-
-
Save timc1/fa5d9f3379f77cb8bf09ffa9f069a9b5 to your computer and use it in GitHub Desktop.
Debounced media query HOC to allow users to render components based on screen width
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 React from 'react' | |
import { debounce } from '../../utils' | |
const withMedia = Component => props => { | |
const [width, setWidth] = React.useState(window.innerWidth) | |
const toggleMedia = debounce(() => { | |
setWidth(window.innerWidth) | |
}, 250) | |
React.useEffect(() => { | |
// Add event listener on mount | |
window.addEventListener('resize', toggleMedia) | |
// Cleanup on unmount | |
return () => window.removeEventListener('resize', toggleMedia) | |
}, []) | |
return <Component {...props} media={width} /> | |
} | |
export default withMedia |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment