Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect element reference height change

Is it possible to detect when an element reference changes it's height? I tried using the following, but when the height of the element changes for whatever reason, the change is not detected. (Please consider that this must also work in IE11)

useEffect(() => {
  // detect change in reference height
}, [elementRef])
like image 893
Andrei Rosu Avatar asked Aug 31 '25 14:08

Andrei Rosu


1 Answers

I noticed another answer mentioning to use a ResizeObserver, but the answer is incomplete, so I'd like to add my own.

Using useEffect

You can create a ResizeObserver inside a useEffect-hook, and then do what you want to do when the element changes its size. Remember to disconnect from the resizeObserver in the cleanup function.

useEffect(() => {
  if (!elementRef.current) return;
  const resizeObserver = new ResizeObserver(() => {
    // Do what you want to do when the size of the element changes
  });
  resizeObserver.observe(elementRef.current);
  return () => resizeObserver.disconnect(); // clean up 
}, []);

Using useCallback

As mentioned in the comments, it's also possible to use useCallback instead of useEffect.

You can create a ResizeObserver inside a useCallback-hook, and then do what you want to do when the element changes its size. React has an example on how to measure a DOM node.

const elementRef = useCallback(node => {
  if (!node) return;
  const resizeObserver = new ResizeObserver(() => { 
    // Do what you want to do when the size of the element changes
  });
  resizeObserver.observe(node);
}, []);
like image 145
John Avatar answered Sep 02 '25 11:09

John



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!