Skip to content

Instantly share code, notes, and snippets.

@tbjgolden
Created May 8, 2019 06:20
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 tbjgolden/a56d95faff31de6cce0e1b213740612b to your computer and use it in GitHub Desktop.
Save tbjgolden/a56d95faff31de6cce0e1b213740612b to your computer and use it in GitHub Desktop.
withWindowWidth React Higher Order Component (HOC) using Hooks
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;
@tbjgolden
Copy link
Author

(This doesn't contain any debounce logic)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment