Created
May 8, 2019 06:20
-
-
Save tbjgolden/a56d95faff31de6cce0e1b213740612b to your computer and use it in GitHub Desktop.
withWindowWidth React Higher Order Component (HOC) using Hooks
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, { useState, useEffect, useRef } from 'react'; | |
window.windowWidthListeners = window.windowWidthListeners || {}; | |
window.prevWidth = window.prevWidth || window.innerWidth; | |
window.addEventListener('resize', () => { | |
if (window.prevWidth !== window.innerWidth) { | |
window.prevWidth = window.innerWidth; | |
Object.values(window.windowWidthListeners).forEach(fn => fn(window.prevWidth)); | |
} | |
}); | |
const withWindowWidth = WrappedComponent => props => { | |
const [windowWidth, setWindowWidth] = useState(window.innerWidth); | |
const uid = useRef(`${Date.now()}${Math.random()}`); | |
useEffect(() => { | |
window.windowWidthListeners[uid.current] = w => setWindowWidth(w); | |
return () => delete window.windowWidthListeners[uid.current]; | |
}, []); | |
return <WrappedComponent windowWidth={windowWidth} {...props} />; | |
}; | |
export default withWindowWidth; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(This doesn't contain any debounce logic)