DEV Community

Cover image for How to call method on browser resize in react
Chetan Rohilla
Chetan Rohilla

Posted on • Updated on • Originally published at

How to call method on browser resize in react

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);
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;

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

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);
Enter fullscreen mode Exit fullscreen mode

That's it. Please support and like to motivate me to write more.

For More Tutorials Please visit my website readymadecode.

Happy Coding :)

Top comments (0)