Blog>
Snippets

Optimizing React Chart Performance

Show how to use React.memo and useCallback to prevent unnecessary re-renders of a chart component when data updates occur.
const ChartComponent = React.memo(({ data }) => {
  // Chart rendering logic here
});
Wraps the ChartComponent in React.memo, preventing it from re-rendering if props haven't changed. This is key for performance when the parent component re-renders.
const fetchChartData = useCallback(async () => {
  const newData = await fetchData();
  setData(newData);
}, [fetchData]);
Uses useCallback to memoize the fetchChartData function, ensuring that it's only recreated if fetchData changes. This is crucial to avoid unnecessary re-renders caused by function recreation.
useEffect(() => {
  fetchChartData();
}, [fetchChartData]);
This useEffect hook is dependent on fetchChartData. By passing the memoized version of fetchChartData, we ensure that the effect only runs when the fetchData function changes, rather than on every render.