Blog>
Snippets

Optimizing Chart Rerenders with React.memo

Demonstrate how to wrap a TanStack React Chart in React.memo to prevent unnecessary rerenders, especially useful when chart data hasn't changed.
import React from 'react';
import { Chart } from 'tanstack-react-charts';
First, we import React and the Chart component from 'tanstack-react-charts'.
const ChartComponent = React.memo(({ data }) => {
  // Render the chart using the data prop
  return <Chart data={data} />;
}, (prevProps, nextProps) => {
  // Custom comparison function
  return prevProps.data === nextProps.data;
});
We define a ChartComponent and wrap it with React.memo to prevent unnecessary re-renders. React.memo will only allow the component to re-render if the data prop changes. We provide a custom comparison function as the second argument to React.memo, which compares the previous and next data props for equality.
export default ChartComponent;
Finally, we export the ChartComponent for use in our application. This component will now re-render only when the data prop provided to it changes, improving the performance of our application when dealing with complex charts.