Home > Web Front-end > JS Tutorial > How Can I Trigger Re-Rendering in React Upon Browser Window Resize?

How Can I Trigger Re-Rendering in React Upon Browser Window Resize?

Patricia Arquette
Release: 2024-10-19 19:37:29
Original
567 people have browsed it

How Can I Trigger Re-Rendering in React Upon Browser Window Resize?

How to Trigger a React Re-render on Browser Window Resize

Context

In React, optimizing view updates based on external factors like browser window resizing is crucial, especially for layouts. One approach is to leverage the browser's window resize event.

React Hook Approach

Modern React employs hooks to handle such scenarios elegantly. You can create a custom hook that listens to resize events:

<code class="javascript">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;
}</code>
Copy after login

This hook can be used in any component that requires window size information for re-rendering.

React Class-Based Component Approach

For class-based components, listening to the resize event in componentDidMount is recommended. This ensures that the component updates its state with the initial screen dimensions:

<code class="javascript">import React from 'react';

class ShowWindowDimensions extends React.Component {
  state = { width: 0, height: 0 };
  render() {
    return (
      <span>
        Window size: {this.state.width} x {this.state.height}
      </span>
    );
  }
  updateDimensions = () => {
    this.setState({
      width: window.innerWidth,
      height: window.innerHeight
    });
  };
  componentDidMount() {
    window.addEventListener('resize', this.updateDimensions);
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.updateDimensions);
  }
}</code>
Copy after login

By employing these techniques, you can effortlessly trigger React re-renders when the browser window is resized, ensuring optimal layout updates and responsive behavior for your application.

The above is the detailed content of How Can I Trigger Re-Rendering in React Upon Browser Window Resize?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template