Skip to content

Instantly share code, notes, and snippets.

@timc1
Last active March 19, 2019 01:17
Show Gist options
  • Save timc1/fa5d9f3379f77cb8bf09ffa9f069a9b5 to your computer and use it in GitHub Desktop.
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
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