Blog>
Snippets

Optimizing Chart Renders with useMemo Hook

Demonstrate how to use the useMemo hook in React to reduce unnecessary renders for a component that displays a complex dataset using TanStack React Charts.
import React, { useMemo } from 'react';
import { Chart } from 'react-chartjs-2';
Import the necessary React and Chart.js components.
const MyChartComponent = ({ data }) => {
  const memoizedChartData = useMemo(() => ({
    labels: data.labels,
    datasets: [
      {
        label: data.label,
        data: data.values,
        backgroundColor: 'rgba(255, 99, 132, 0.2)'
      }
    ]
  }), [data.labels, data.values, data.label]);
Use the useMemo hook to memorize the computed data for the chart. The dependency array includes data that might change and trigger a re-render.
  return (
    <Chart
      type='bar'
      data={memoizedChartData}
    />
  );
};
Render the Chart component using the memoized data.