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:
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):
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):
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.
