DEV Community

Bennett Upfield
Bennett Upfield

Posted on

ResizeObserver & UseState

Just a Short Post

I ran into a problem while using ResizeObserver and UseState which led to a reload loop. The problem I found out is that when a ResizeObserver is called on an element even though its not being resized it decides to call the attached function. So, since this is the case the solution is pretty simple, if you change a useState inside the function have a variable outside the function that changes after the first call,

const e = true;
observer.current = new ResizeObserver(entries =>{
            for(let entry of entries){
                if(e !== 1)
                {
                    //Very Useful Code
                }
                e = false;
            }
        }); 
Enter fullscreen mode Exit fullscreen mode

Pretty simple stuff, but really annoying to find out that ResizeObserver calls on every single assignment.

Discussion (0)