What is the best practice to get the width of a React component after it's been resized?

Viewed 60

I have a resizable button, and need to get the width as soon as it's been resized:

useEffect(() => {
      if (myRef.current) setButtonWidth(myRef.current.offsetWidth);
    }, [myRef.current?.offsetWidth]);

This works as it should, getting the width after every resize, but it's my understanding that it's an anti-pattern to put a ref in a useEffect like this?

What would be the best practice to go about getting the width of the component after each resize?

1 Answers

To get the size of a dom element using a ref is completely okay. However, using a Resize Observer would be a more canonical way to track an element's size.

Related