Skip to content
Advertisement

How to add debounce to useElementSize hook?

I am using the following hook in order to get the width and the height for an element:

JavaScript

It works perfectly – when I resize the window I see that the component re-renders every time I resize and it happens very fast.

The problem is I have a very big element and I would like to add a debounce to the useElementHook. I tried to add a debounce of 2 seconds but I get the following behavior:

This is what I tried:

JavaScript

Current behavior: Resize event -> doesn’t do anything -> 2 seconds have passed -> I see 40 console.logs (the component still re-renders 40 times instead of once).

What I want: Resize event -> doesn’t do anything -> 2 seconds have passed -> 1 console.log and re-render the component once!

Is there any solution for this?

Advertisement

Answer

I’ve made some changes to your implementation to make it work: Notable changes:

  • move handleSize inside the effect (no need for useCallback
  • use a ref to the node to avoid a dependency to the effect
JavaScript

Edit nervous-surf-ei3wmx

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement