Blog>
Snippets

Optimizing Performance for Real-Time Data Updates

Illustrate techniques for optimizing a financial dashboard that receives real-time data updates, focusing on efficient chart re-rendering with React hooks like useMemo and useCallback.
const FinancialChart = ({ data }) => {
  const memoizedData = useMemo(() => data, [data]);

  return (
    <YourChartLibraryComponent data={memoizedData} />
  );
};
This snippet demonstrates the use of useMemo to memoize the data prop passed to a chart component. This ensures that the chart only re-renders when the data actually changes, improving performance for real-time updates.
const fetchData = useCallback(async () => {
  const response = await fetch('your-api-endpoint');
  const newData = await response.json();
  setData(newData);
}, []);
This snippet shows how to use useCallback to memoize a data-fetching function. This is useful in cases where the function needs to be passed as a prop or has dependencies, ensuring that it does not get recreated on every render.
useEffect(() => {
  const interval = setInterval(fetchData, 5000);

  return () => clearInterval(interval);
}, [fetchData]);
This snippet uses useEffect along with the memoized fetchData function from the previous example to set up a polling mechanism for real-time data. It fetches new data every 5 seconds without causing unnecessary re-renders.