import React, { useLayoutEffect, useState } from 'react';
function useWindowSize() {
const [size, setSize] = useState([0, 0]);
useLayoutEffect(() => {
function updateSize() {
setSize([window.innerWidth, window.innerHeight]);
}
window.addEventListener('resize', updateSize);
updateSize();
return () => window.removeEventListener('resize', updateSize);
}, []);
return size;
}
function ShowWindowDimensions(props) {
const [width, height] = useWindowSize();
return <span>Window size: {width} x {height}</span>;
}
const [dimensions, setDimensions] = useState({
height: typeof window !== 'undefined' && window.innerHeight,
width: typeof window !== 'undefined' && window.innerWidth,
});
useEffect(() => {
const handleResize = () => {
setDimensions({
height: window.innerHeight,
width: window.innerWidth,
});
};
window.addEventListener('resize', handleResize);
}, []);
return {
{console.log(`Rendered at ${dimensions.width} x ${dimensions.height}`)}
}