I recently came across this video from a tutorial series on D3 + React. In this video, to resize the graph, a custom hook is created that uses ResizeObserver:
const useResizeObserver = ref => {
const [dimensions, setDimensions] = useState(null);
useEffect(() => {
const observeTarget = ref.current;
const resizeObserver = new ResizeObserver(entries => {
entries.forEach(entry => {
setDimensions(entry.contentRect);
});
});
resizeObserver.observe(observeTarget);
return () => {
resizeObserver.unobserve(observeTarget);
};
}, [ref]);
return dimensions;
};
I've always seen previously / used before the viewBox attribute to make SVG's responsive, as this article (and many others) discusses. My question is: is there a reason (performance, simplicity) to use this useResizeObserver custom hook over simply using viewBox? With viewBox, I don't need to create a custom hook, or have a wrapper div around my SVGs (as he explains in the video), or have to use refs... viewBox seems simpler. However, apparently ResizeObserver is a new API to get the dimensions of elements, and perhaps there are advantages to using it over viewBox that are not obvious.


