Blog>
Snippets

Wrapping a Chart Component with React.memo

Shows how to wrap a TanStack React Chart component with React.memo to prevent unnecessary re-renders when props have not changed.
import React, { memo } from 'react';
import { Chart } from 'react-chartjs-2';
Imports React and its memo function, along with the Chart component from react-chartjs-2.
const ChartComponent = ({ data }) => {
  return (
    <div>
      <Chart data={data} />
    </div>
  );
};
Defines a ChartComponent function component that receives data as props and renders a Chart wrapped in a div.
const MemoizedChartComponent = memo(ChartComponent, (prevProps, nextProps) => {
  return prevProps.data === nextProps.data;
});
Wraps the ChartComponent with React.memo to prevent unnecessary re-renders. Uses a custom comparison function to check if the data prop has changed.