Blog>
Snippets

Using useMemo for Optimizing Chart Re-renders

Provide a code example that uses the useMemo hook to memoize complex calculations in chart data, preventing unnecessary re-renders.
const memoizedChartData = React.useMemo(() => transformDataForChart(rawData), [rawData]);
This code snippet shows how to use the useMemo hook to memoize the result of a complex data transformation needed for chart rendering. The transformation function 'transformDataForChart' is only called when 'rawData' changes, preventing unnecessary recalculations and re-renders.
const MyChartComponent = ({ data }) => {
  const memoizedData = React.useMemo(() => data.map(item => expensiveDataTransformation(item)), [data]);
  return <Chart data={memoizedData} />;
};
Here, useMemo is utilized to memoize an expensive data transformation inside a functional chart component. The transformation only happens when the 'data' prop changes, optimizing performance by reducing unnecessary re-renders.