Rerender view on browser resize with React. You can define a custom Hook that listens to the window resize event, something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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>; } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.