Search code examples
reactjssettimeoutaddeventlistenerdebouncing

React set dimensions on window resize using debounce method


I am trying to set the window dimensions during window resize event using a debounce method. It seems that the dimensions are set only the first time that the code runs. When i am trying to resize the window the dimensions does not change. I create a sandbox example https://codesandbox.io/s/react-example-ciq1l


Solution

  • You don't need to set timer inside return part of debounce.

    Another thing, any time you get inside debounce function you are assigned new var timer, so the check of if (timer) right after never gonna apply

    // inside contructor
    this.timerRef = React.createRef(null) // for react version > 16.3
    
    debounce(func) {
          if (this.timerRef.current) clearTimeout(this.timerRef.current);
          this.timerRef.current = setTimeout(func, 100);
      } 
    

    Edit

    Because you want to pass param to the event listener function (and need to use () activation), you suppose to take the whole function as a callback

     window.addEventListener(
          "resize", () =>  //adding () =>
          this.debounce(() => {
            this.updateDimensions();
          })
        );
    

    or inside debounce you can refer directly to this.updateDimensions, and there is no need to pass func anymore and you can do like

    window.addEventListener("resize", this.debounce)
    

    without activate debounce()