@massds/mayflower-react
Version:
React versions of Mayflower design system UI components
29 lines • 916 B
JavaScript
import React from "react";
const useWindowWidth = () => {
// We use state here so that a default can be set based on window,
// if window exists.
const _React$useState = React.useState(null),
windowWidth = _React$useState[0],
setWindowWidth = _React$useState[1];
const resize = React.useCallback(() => {
if (window) {
setWindowWidth(window.innerWidth);
}
}, [setWindowWidth]);
React.useEffect(() => {
// Set default windowWidth to window.innerwidth if window exists.
if (window) {
setWindowWidth(window.innerWidth);
// Update windowWidth on window resize.
window.addEventListener('resize', resize);
}
return () => {
if (window) {
// Remove resize event on unmount of component.
window.removeEventListener('resize', resize);
}
};
}, [resize, setWindowWidth]);
return windowWidth;
};
export default useWindowWidth;