Blog>
Snippets

Optimizing TanStack Chart Renders with useMemo hook

Demonstrate how to use the React useMemo hook to prevent unnecessary rerenders of TanStack React Charts when the chart data hasn’t changed.
import React, { useMemo } from 'react';
import { Chart } from 'tanstack-react-charts';
Imports the React library with the useMemo hook, and the Chart component from tanstack-react-charts.
const ChartComponent = ({data}) => {
  const memoizedData = useMemo(() => data, [data]);
Defines a ChartComponent that receives 'data' as props. Uses the useMemo hook to memorize the 'data' prop, so it only recalculates when 'data' changes, preventing unnecessary rerenders.
  return (
    <Chart
      options={/* Chart options here */}
      data={memoizedData}
    />
  );
};
Renders the Chart component with the memoized data. By passing memoizedData as the data prop, the component ensures that the Chart only rerenders when its data actually changes.
export default ChartComponent;
Exports the ChartComponent for use in other parts of the application.