Tracks the dimensions of the browser window.
useState()
hook to initialize a state variable that will hold the window's dimensions. Initialize with both values set to undefined
to avoid mismatch between server and client renders.Window.innerWidth
and Window.innerHeight
to update the state variable.useEffect()
hook to set an appropriate listener for the 'resize'
event on mount and clean it up when unmounting.const useWindowSize = () => {
const [windowSize, setWindowSize] = React.useState({
width: undefined,
height: undefined,
});
React.useEffect(() => {
const handleResize = () =>
setWindowSize({ width: window.innerWidth, height: window.innerHeight });
window.addEventListener('resize', handleResize);
handleResize();
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return windowSize;
};
const MyApp = () => {
const { width, height } = useWindowSize();
return (
<p>
Window size: ({width} x {height})
</p>
);
};
ReactDOM.render(<MyApp />, document.getElementById('root'));
React, Hooks
Tracks the browser's location search param.
React, Hooks
Tracks the browser's location hash value, and allows changing it.
React, Hooks
Checks if the code is running on the browser or the server.