Categories
React Answers

How to Rerender the View on Browser Resize with React?

Spread the love

Sometimes, we want to re-render the view on browser resize with React.

In this article, we’ll look at how to re-render the view on browser resize with React.

Rerender the View on Browser Resize with React

We can use the useLayoutEffect to add the event listener that runs when the window resizes.

And in the window resize event handler, we can run our code to change a state to make the view rerender.

For instance, we can write:

import React, { useLayoutEffect, useState } from "react";

const useWindowSize = () => {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    const updateSize = () => {
      setSize([window.innerWidth, window.innerHeight]);
    };
    window.addEventListener("resize", updateSize);
    updateSize();
    return () => window.removeEventListener("resize", updateSize);
  }, []);
  return size;
};

export default function App() {
  const [width, height] = useWindowSize();
  return (
    <span>
      Window size: {width} x {height}
    </span>
  );
}

We create the useWindowSize hook that has the size state.

In the useLayoutEffect hook callback, we create the updateSize function that calls setSize to set thje size state to an array with window.innerWidth and window.innerHeight , which has the width and height of the browser window respectively.

Then we call window.addEventListener with 'resize' to set updateSize as the window resize event listener.

Also, we return a function that calls window.removeEventListener to clear the resize event listener when the component unmounts.

Finally, we return the size at the end of the hook function.

Then in App , we destructure the width and height returned from the useWindowSize hook.

And then we render it in the span.

Now when the window resizes, we see its size change.

Conclusion

We can use the useLayoutEffect to add the event listener that runs when the window resizes.

And in the window resize event handler, we can run our code to change a state to make the view rerender.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *