Blog>
Snippets

Using useCallback for Chart Event Handlers

Provides an example of using useCallback to memoize event handler functions passed as props to chart components, preventing unnecessary re-renders.
import React, { useCallback } from 'react';
import { Chart } from 'chart.js';
Import necessary libraries and hooks.
const ChartComponent = ({ data }) => {
  const chartRef = React.useRef(null);

  const updateChart = useCallback(() => {
    const chartInstance = chartRef.current;
    if (chartInstance) {
      chartInstance.data = data;
      chartInstance.update();
    }
  }, [data]);
Define a ChartComponent with data props. Use useCallback to memoize the updateChart function, which updates the chart with new data. The dependency array contains data, so updateChart is only recreated if data changes.
React.useEffect(() => {
    const ctx = chartRef.current.getContext('2d');
    const myChart = new Chart(ctx, {
      type: 'bar',
      data: data,
      options: {...}
    });
    chartRef.current = myChart;

    return () => myChart.destroy();
  }, [data]);
Use React's useEffect hook to initialize the chart when the component mounts and destroy it on unmount to prevent memory leaks.
return (
    <div>
      <canvas ref={chartRef} />
      <button onClick={updateChart}>Update Chart</button>
    </div>
  );
};
Return a canvas element for Chart.js to render the chart and a button to trigger the updateChart function.
export default ChartComponent;
Export the ChartComponent for use in other parts of the application.