I have a React application where I've created a line chart with zoom and panning capabilities. Each data point in the chart is a separate react component.
The zoom gets triggered on the event zoom in the parent container, the zoomTransform is then used to calculate a new x- and y-scales called zoomedXScale and zoomedYScale. Once these new scales has been calculated the useEffect in the rendered components gets called and the x and y coordinates are updated.
The zoom function in the parent container:
const zoomed = d3
.zoom()
.extent([
[0, 0],
[width, height]
])
.scaleExtent([MinZoom, MaxZoom]) // This control how much you can unzoom (x0.5) and zoom (x20)
.translateExtent([
[0, 0],
[width, height]
])
.on('zoom', (e: d3.D3ZoomEvent<SVGElement, unknown>) => {
const zoomState = e.transform;
setCurrentZoomState(zoomState);
});
Example of useEffect in child component rendered in the svg:
useEffect(() => {
const image = d3.select(ref.current);
image
.attr('x', zoomedXScale(price))
.attr('y', zoomedYScale(price));
}, [price, zoomedXScale, zoomedYScale, zoomTransform]);
The performance issue occurs when there is about 500-1000 components which gets rendered and each x- and y coordinates are updated for every zoom event, it gets very slow.
One possible solution i thought of after reading other related posts is to only render the points inside the current viewport. But I also wanted to know if there is a more efficient solution for updating coordinates for the different components in a React application using d3 with zoom and panning in a linechart.