1

Let's say I have a component:

function Component({ children }) {
  const ref = useRef(null);

  useEffect(() => {
    // do something based on ref.current size
  }, [])

  return <div ref={ref}>{children}</div>;
}

I would like to do something based on the change of the size of the div. The size will change when the children changes. However, with the currect code, useEffect will only fire once and won't react to children change.

I can't put ref in the dependencies array as this won't retrigger useEffect.

useEffect(() => {
  // no effect
}, [ref]);

I could put children in the array but this smells wrong - it's definitely an antipattern.

useEffect(() => {
  // works but blah
}, [children]);

What would be the idiomatic react way to handle this case?

apieceofbart
  • 2,048
  • 4
  • 22
  • 30

0 Answers0