ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Sunday, November 13, 2022

[FIXED] How to observe when window resize stop in React

 November 13, 2022     javascript, reactjs, resize   

Issue

I want to observer when window stop resizing, cause currently if i listen to the resize event on window, i could only listen to resizing change but not knowing when resizing stops. I checked the event parameter in resizing callback, but did not find and helpful information.

Below is the code i'm trying to complete:

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

export default function App() {
  const [windowResizing, setWindowResizing] = useState(false);

  const handleWindowResize = e => {
    setWindowResizing(true);
  };

  useEffect(() => {
    window.addEventListener("resize", handleWindowResize);

    return () => window.removeEventListener("resize", handleWindowResize);
  }, []);

  return <div>{JSON.stringify({ windowResizing })}</div>;
}

But this does not work, since windowResizing will keep being true after resizing begins, even i already stops resizing.

So is there any way to observe when window stop resizing and i can then call setState based on that?


Solution

There is no real "resizing state" in the browser; the resize event occurs and then it's over.

You could emulate a resizing state of your own by setting a state variable to true on every resize event, and start a new timeout that will reset it back to false after a small amount of time.

Example

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

export default function App() {
  const [windowResizing, setWindowResizing] = useState(false);

  useEffect(() => {
    let timeout;
    const handleResize = () => {
      clearTimeout(timeout);

      setWindowResizing(true);

      timeout = setTimeout(() => {
        setWindowResizing(false);
      }, 200);
    }
    window.addEventListener("resize", handleResize);

    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return <div>{JSON.stringify({ windowResizing })}</div>;
}


Answered By - Tholle
Answer Checked By - - Clifford M. (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix