How to call method on browser resize in react

React Native, ReactJS

Sometimes, we have to do some functionality on browser resize in react. In this tutorial we will learn how to call method on browser resize in react. And we can do this in functional or class component.

Window Resize in Functional Component using React Hooks

To do this we can define a custom Hook that listens to the window resize event. Use the code given below.

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;
}

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

We can now use useWindowSize as function by exporting it using export default function useWindowSize. We can also use useWindowSize as hooks in other functional components. useLayoutEffect it is like as useEffect. But It is called synchronously after all DOM mutations.

Window Resize in Class Component

Here we are using componentDidMount method which is a part of React-Lifecyle. It is called after the component is rendered or when our component got updated. Using componentDidMount we can execute the React code when the component is already placed in the DOM.

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);
  }
}

In the above example we have gets window width and height on resize using the class and functional components. You can call method on browser resize in react whatever you required in react.js or react native.

Recommendation

How to validate form in ReactJS

How to create charts in ReactJS

For moreĀ ReactJS Tutorials Click here.

If you like this, share this.

Follow us on FacebookTwitterTumblrLinkedInYouTube.