Blog>
Snippets

Custom Comparison Function for React.memo

Illustrates how to implement a custom comparison function for React.memo to fine-tune when a chart component should update, based on specific prop changes.
import React, { memo } from 'react';
import { Chart } from 'chart.js';
Import necessary dependencies from react and chart.js.
const areEqual = (prevProps, nextProps) => {
  return prevProps.data === nextProps.data && prevProps.title === nextProps.title;
};
Define a custom comparison function to check if the 'data' and 'title' props are equal between the current and next props. This determines if the component should re-render.
const ChartComponent = memo(({ data, title }) => {
  // Component logic for rendering the chart
  useEffect(() => {
    const chart = new Chart(document.getElementById('chart'), {
      type: 'line',
      data: data,
      options: { title: { display: true, text: title } }
    });
    return () => chart.destroy();
  }, [data, title]);

  return <canvas id="chart"></canvas>;
}, areEqual);
Wrap the chart component with React.memo and pass the custom comparison function as the second argument to prevent unnecessary re-renders. Use useEffect to handle the chart rendering and cleanup.