Home  >  Article  >  Web Front-end  >  How to Re-render View on Browser Resize in React: jQuery vs. React Hooks and Classes?

How to Re-render View on Browser Resize in React: jQuery vs. React Hooks and Classes?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 19:33:30440browse

How to Re-render View on Browser Resize in React: jQuery vs. React Hooks and Classes?

Rerender View on Browser Resize with React

Background

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.

Code

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:

Question

Instead of using jQuery's window resize event, is there a more "React" way to listen for browser resize events and trigger re-rendering?

Answer

Using React Hooks

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>

Using React Classes

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!

Statement:
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