React + TypeScript: Re-render a Component on Window Resize

Updated: March 3, 2023 By: A Goodman 4 comments

This article shows you how to re-render a React component when the window (the document view) gets resized. We’ll cover the basics and then build a complete example with modern things like hooks, functional components, and TypeScript.

Overview

Currently, React doesn’t support an event named onResize or anything like that. However, we can use the window.resize event that is supported natively by web browsers. This event fires when the window has been resized.

You can set up the event handler function in one of two ways below:

window.addEventListener('resize', myHandlerFunction);

Or:

window.resize = myHandlerFunction;

Implement with the useEffect hook:

 useEffect(() => {
    window.addEventListener('resize', myHandlerFunction);

    // You can also use:
    // window.onresize = myHandlerFunction;
  }, []);

To re-render one component (or many components) when the user resizes the window, we can use the useState hook. For more clarity and get a practical sense, see the end-to-end example below.

The Example

App Preview

The React app we are going to build displays the width and height of the window. When the width is less than or equal to 500px, the background will be white. When the width is from 501px to 700px, the background will be green. Otherwise, the background is orange.

Here’s how it works:

The Code

1. Create a new React TypeScript project:

npx create-react-app kindacode_example --template typescript

The name doesn’t matter. Choose whatever you like.

2. Full source code in src/App.tsx with explanations:

// App.tsx
// Kindacode.com
import React, { useState, useEffect } from "react";

// Create an interface for the size of the window
interface Size {
  width: number;
  height: number;
}

const App = () => {
  // The size of the window
  const [size, setSize] = useState<Size>();

  // This function updates the state thus re-render components
  const resizeHanlder = () => {
    const width = window.innerWidth;
    const height = window.innerHeight;

    setSize({
      width: width,
      height: height,
    });
  };

  // Listening for the window resize event
  useEffect(() => {
    window.addEventListener('resize', resizeHanlder);

    // Cleanup function
    // Remove the event listener when the component is unmounted
    return () => {
      window.removeEventListener('resize', resizeHanlder);
    }
  }, []);

  return (
    <div
      // Change the backgronund color according to the window's width
      style={{
        ...styles.container,
        backgroundColor:
          !size || size.width <= 500
            ? "white"
            : size && size.width <= 700
            ? "green"
            : "orange",
      }}
    >
      {/* Display width and height as text */}
      {size && (
        <>
          <h2>Width: {size.width}</h2>
          <h2>Height: {size.height}</h2>
        </>
      )}

      {!size && <h2>Use your mouse to resize the window</h2>}
      <h5>Welcome to KindaCode.com</h5>
    </div>
  );
};

// Style the container
const styles = {
  container: {
    width: "100vw",
    height: "100vh",
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
  },
} as const;

export default App;

3. Run the project and head to http://localhost:3000 to check the result:

npm start

Conclusion

You’ve learned how to update components on window resize. If you’d like to learn more new and interesting things about React, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Subscribe
Notify of
guest
4 Comments
Inline Feedbacks
View all comments
playerony
playerony
1 year ago

I didn’t find such a package on npm and I thought it would be nice to create one: https://www.npmjs.com/package/use-device-detect. I think it will help someone 🙂

Gautam shukla
Gautam shukla
2 years ago

I have used this above code my side is working great. Thanks

Related Articles