Home > Article > Web Front-end > How to Re-render View on Browser Resize in React: jQuery vs. React Hooks and Classes?
Utilizing React, you can dynamically adjust the layout of elements on a web page based on browser window size. However, you may encounter issues when the window resizes and the view doesn't automatically update. This article addresses a common question: how to trigger a re-render when the browser window is resized.
Consider the following React application with a component hierarchy consisting of a MyApp component, a Block component representing individual blocks on the page, and a Blocks component representing a collection of blocks:
Instead of using jQuery's window resize event, is there a more "React" way to listen for browser resize events and trigger re-rendering?
React Hooks provide a cleaner and more functional approach. You can create a custom Hook that listens to the window resize event:
<code class="javascript">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; }</code>
In React classes, you can listen for resize events in the componentDidMount lifecycle method:
<code class="javascript">componentDidMount() { window.addEventListener('resize', this.updateDimensions); } componentWillUnmount() { window.removeEventListener('resize', this.updateDimensions); }</code>
This approach is more verbose but still provides a clean implementation.
The above is the detailed content of How to Re-render View on Browser Resize in React: jQuery vs. React Hooks and Classes?. For more information, please follow other related articles on the PHP Chinese website!