Blog>
Snippets

Implementing Memorization for Performance

Illustrate using TypeScript with React's useMemo hook to optimize the performance of a TanStack React Chart by preventing unnecessary re-renders.
import { useMemo } from 'react';
import { Chart } from 'tanstack-react-charts';
Import necessary hooks and components.
const processData = (data) => {
  // Assume this function processes and aggregates data for the chart
  return data.map(item => ({...item, value: item.value * 2}));
};
Define a function for data processing. This is a placeholder for any data manipulation required before feeding it into the chart.
const MyChartComponent = ({ data }) => {
  const memoizedData = useMemo(() => processData(data), [data]);
  
  return (
    <Chart
      options={{
        data: memoizedData
      }}
    />
  );
};
Use the useMemo hook to memoize processed chart data. This prevents re-processing of data on every render, only updating when the 'data' prop changes.