Blog>
Snippets

Implementing Custom Hooks for Chart Data Memoization

Provide an example of a custom hook that uses `useMemo` for memoizing data passed to a TanStack React Chart, preventing unnecessary rerenders and enhancing performance.
import { useMemo } from 'react';
Firstly, import useMemo from React, which will be used for memoizing the chart data.
const useChartData = (data) => {
  const memoizedData = useMemo(() => ({
    labels: data.labels,
    datasets: [{
      label: data.datasetLabel,
      data: data.values,
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      borderColor: 'rgba(255, 99, 132, 1)',
      borderWidth: 1
    }]
  }), [data.labels, data.values, data.datasetLabel]);
  
  return memoizedData;
};
Defines a custom hook called useChartData for memoizing chart data. This hook takes an object 'data' as its argument, which contains labels, values, and datasetLabel. The useMemo hook then creates a memoized version of this data object, which only recomputes when any of the dependencies (labels, values, datasetLabel) change. This efficiency prevents unnecessary re-renders when the data hasn't changed.
export default useChartData;
Exports the custom hook, so it can be imported and used in components that render charts.