React ResizeObserver Hook: Avoiding Observer Re-creation When a Callback Dependency Changes

TechLab Editorial TeamPublished 72 views1 answer
0

Editorial Q&A · This problem and its answer were written by the TechLab editorial team to document a common issue. It isn't a question from a community member. If you've hit a variation of it or know a better approach, add a reply below.

The problem

A dashboard (React 18, TypeScript) has resizable chart panels. A custom hook, usePanelDimensions, uses ResizeObserver to track a panel's size and passes it to the chart inside. The hook also applies a scaleFactor (for example, a density setting) to the measured size.

The measurement callback is wrapped in useCallback with scaleFactor as a dependency, and the effect that creates the ResizeObserver depends on that callback. So every time scaleFactor changes, the effect cleans up (disconnect()) and creates a new observer.

The goal: create the observer once on mount and disconnect it on unmount, while the reported dimensions still reflect the current scaleFactor.

A simplified version of the hook and components:

hooks/usePanelDimensions.ts:

TypeScript
import { useState, useEffect, useRef, useCallback } from 'react';

interface Dimensions {
  width: number;
  height: number;
}

const usePanelDimensions = <T extends HTMLElement = HTMLDivElement>(): [Dimensions, React.RefObject<T>] => {
  const [dimensions, setDimensions] = useState<Dimensions>({ width: 0, height: 0 });
  const [scaleFactor, setScaleFactor] = useState(1); // Imagine this can change dynamically
  const ref = useRef<T>(null);
  const animationFrameRef = useRef<number | null>(null);

  // This callback changes whenever scaleFactor changes
  const updateDimensions = useCallback(() => {
    if (ref.current) {
      const { clientWidth, clientHeight } = ref.current;
      setDimensions({
        width: clientWidth * scaleFactor,
        height: clientHeight * scaleFactor,
      });
    }
  }, [scaleFactor]); // <--- Dependency on scaleFactor

  useEffect(() => {
    const element = ref.current;
    if (!element) return;

    // This wrapper function needs to be stable for ResizeObserver, but calls updateDimensions
    const handleResize = (entries: ResizeObserverEntry[]) => {
      // Debounce with requestAnimationFrame for smoother updates
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
      animationFrameRef.current = requestAnimationFrame(() => {
        updateDimensions(); // <--- Calls the potentially re-created callback
      });
    };

    const resizeObserver = new ResizeObserver(handleResize);
    resizeObserver.observe(element);

    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
      resizeObserver.disconnect();
    };
  }, [updateDimensions]); // <--- This dependency causes re-initialization

  // For demonstration, expose a way to change scaleFactor
  useEffect(() => {
    const timer = setInterval(() => {
      setScaleFactor(prev => (prev === 1 ? 1.05 : 1));
    }, 3000);
    return () => clearInterval(timer);
  }, []);

  return [dimensions, ref];
};

export default usePanelDimensions;

components/ResizablePanel.tsx (simplified):

TypeScript
import React from 'react';
import usePanelDimensions from '../hooks/usePanelDimensions';

interface ResizablePanelProps {
  children: React.ReactNode;
}

const ResizablePanel: React.FC<ResizablePanelProps> = ({ children }) => {
  const [dimensions, ref] = usePanelDimensions();

  const childrenWithProps = React.Children.map(children, child => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { panelWidth: dimensions.width, panelHeight: dimensions.height });
    }
    return child;
  });

  return (
    <div ref={ref} style={{ flexGrow: 1, position: 'relative', minWidth: 0, minHeight: 0, overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
        {childrenWithProps}
      </div>
      <p>Panel Dims (Scaled): {dimensions.width.toFixed(2)}x{dimensions.height.toFixed(2)}</p>
    </div>
  );
};

export default ResizablePanel;

App.tsx (simplified):

TypeScript
import React from 'react';
import ResizablePanel from './components/ResizablePanel';

const MyChartComponent: React.FC<{ panelWidth: number; panelHeight: number }> = ({ panelWidth, panelHeight }) => {
  return (
    <div style={{ width: '100%', height: '100%', border: '1px solid blue', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
      <p>Chart renders here (uses {panelWidth.toFixed(2)}x{panelHeight.toFixed(2)})</p>
    </div>
  );
};

function App() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh', padding: 20 }}>
      <h1>Dashboard with Resizable Widget</h1>
      <div style={{ flexGrow: 1, display: 'flex', gap: 20 }}>
        <div style={{ flex: 1, border: '1px solid green' }}>
          Fixed Widget
        </div>
        <div style={{ flex: 2, border: '1px solid purple' }}>
          <ResizablePanel>
            <MyChartComponent />
          </ResizablePanel>
        </div>
      </div>
    </div>
  );
}

export default App;

Expected behaviour: The ResizeObserver should be initialized once when the ResizablePanel mounts. Any changes to scaleFactor or the element's size should trigger the updateDimensions logic with the latest scaleFactor value, but without re-initializing the ResizeObserver (i.e., disconnect() and observe() should not be called repeatedly).

Actual behaviour: Every time scaleFactor changes (every 3 seconds in the demo), updateDimensions is re-created, the effect re-runs, and the observer is disconnected and re-created. Logging in the effect confirms disconnect() and observe() run on each change.

Advertisement

1 Answer

0

Why it happens

useCallback([scaleFactor]) returns a new function whenever scaleFactor changes. The observer effect lists that function as a dependency, so React runs the effect's cleanup (disconnect()) and setup (new ResizeObserver(...)) again. React is doing exactly what the dependency array says.

In fairness, re-creating one ResizeObserver every few seconds costs very little. But the design also has a real flaw: the hook stores a derived value (size × scale) in state, so every input change has to go through the observer's callback to update it.

The simplest fix: store the measurement, derive the rest

Keep only what the observer actually measures in state, and compute the scaled size during render. The observer effect then has no dependency on scaleFactor at all, and a scaleFactor change updates the output immediately, with no resize needed:

TypeScript
import { useEffect, useRef, useState } from 'react';

interface Dimensions {
  width: number;
  height: number;
}

function usePanelDimensions<T extends HTMLElement = HTMLDivElement>(scaleFactor = 1) {
  const ref = useRef<T>(null);
  const [size, setSize] = useState<Dimensions>({ width: 0, height: 0 });

  useEffect(() => {
    const element = ref.current;
    if (!element) return;

    const observer = new ResizeObserver(([entry]) => {
      const { inlineSize, blockSize } = entry.contentBoxSize[0];
      // Bail out of re-rendering when nothing changed
      setSize(prev =>
        prev.width === inlineSize && prev.height === blockSize
          ? prev
          : { width: inlineSize, height: blockSize },
      );
    });

    observer.observe(element);
    return () => observer.disconnect();
  }, []); // created once, removed on unmount

  // Derived during render: always uses the current scaleFactor
  const dimensions: Dimensions = {
    width: size.width * scaleFactor,
    height: size.height * scaleFactor,
  };

  return [dimensions, ref] as const;
}

Notes on this version:

  • scaleFactor is a parameter. In the original it was internal state changed by a timer, which only made sense for the demo. Passing it in lets the caller control it, and the hook stays simple.
  • No requestAnimationFrame debounce is needed. ResizeObserver already delivers at most one notification per element per frame, after layout and before paint.
  • contentBoxSize comes from the observer entry, so the callback doesn't read layout properties like clientWidth (which can force an extra layout). clientWidth also includes padding, while the content box doesn't. Choose the box that matches what your chart needs.
  • The functional state update returns the previous object when the size is unchanged, so React skips the re-render.

When the callback genuinely needs the latest values

Sometimes the observer callback has to do something with current props, such as calling an onResize prop or logging with the current settings, rather than just store a measurement. Then keep the callback in a ref and read it from the stable observer:

TypeScript
import { useEffect, useLayoutEffect, useRef } from 'react';

function useResizeObserver<T extends HTMLElement>(onResize: (entry: ResizeObserverEntry) => void) {
  const ref = useRef<T>(null);
  const onResizeRef = useRef(onResize);

  // Keep the ref pointing at the latest callback (layout effect: updated before observers fire)
  useLayoutEffect(() => {
    onResizeRef.current = onResize;
  });

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    const observer = new ResizeObserver(([entry]) => onResizeRef.current(entry));
    observer.observe(element);
    return () => observer.disconnect();
  }, []);

  return ref;
}

React 19.2 added useEffectEvent for exactly this pattern: it wraps a function so it always sees the latest props and state without being an effect dependency. On earlier versions, the ref approach above is the standard workaround.

Edge Cases and Related Pitfalls:

  1. useLayoutEffect for Immediate Measurements: If the component needs to render immediately with the correct dimensions (e.g., to prevent layout shifts or flickering), and those dimensions depend on DOM measurements that occur before the browser paints, useLayoutEffect might be more appropriate than useEffect. useLayoutEffect runs synchronously after all DOM mutations but before the browser paints. For ResizeObserver, useEffect is typically fine as the observer fires asynchronously anyway, but it's a good distinction to know for other DOM interaction hooks.
  2. The ref must be attached at mount: the observer effect runs once, so if the element is rendered conditionally (and ref.current is null on the first run), the observer is never created. For elements that appear later, use a callback ref (ref={node => ...}) that starts and stops observing as the node attaches and detaches.
  3. cloneElement to pass sizes down (as in ResizablePanel) is fragile, since it silently breaks when a child is wrapped in another component. Passing a render function (children(dimensions)) or using context is more robust.

💡 Bonus Tip: Debounce the Expensive Part

If re-rendering the chart is expensive while the user drags a panel edge, debounce the chart's expensive work (for example, re-rendering only once the size has been stable for 100–150 ms), not the measurement. Create the debounced function once (in a ref or useMemo with no changing dependencies), not with useCallback(debounce(fn, 150), [fn]), which creates a new debounce timer every time fn changes and silently stops debouncing.

TechLab Editorial TeamAuthorAnswered

Know the answer?

Posting answers needs a TechLab plan. Reading every discussion stays free.