jbcortez89
jbcortez89

Reputation: 135

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

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?

Upvotes: 1

Views: 677

Answers (1)

Stephen
Stephen

Reputation: 399

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.

Upvotes: 1

Related Questions