Blog>
Snippets

Optimizing performance for React Charts with large datasets

Provide strategies for optimizing React Charts performance, especially when dealing with large datasets from GraphQL queries, including useMemo and useCallback hooks.
import React, { useMemo } from 'react';
import { BarChart, Bar, XAxis, YAxis, Tooltip, Legend } from 'recharts';
import { useQuery } from '@apollo/client';
import { GET_LARGE_DATASET } from './queries';
Imports React, Recharts for chart visualization, Apollo Client for GraphQL queries, and the specific GraphQL query for fetching the large dataset.
const OptimizedChart = () => {
  const { loading, data } = useQuery(GET_LARGE_DATASET);

  // Memoize the dataset to prevent unnecessary recalculations
  const memoizedData = useMemo(() => data?.largeDataset || [], [data]);

  if (loading) return <p>Loading...</p>;

  return (
    <BarChart width={600} height={300} data={memoizedData}>
      <XAxis dataKey="name" />
      <YAxis />
      <Tooltip />
      <Legend />
      <Bar dataKey="value" fill="#8884d8" />
    </BarChart>
  );
};
Defines a React component that uses the Apollo Client to fetch and display the dataset with memoization to optimize rendering performance. It renders a bar chart using the Recharts library.
export default OptimizedChart;
Exports the component for use in other parts of the application.