Blog>
Snippets

Basic Usage of useMemo for Data Preparation

Demonstrates how to use useMemo to preprocess data for a chart component, ensuring data is only recalculated when its dependencies change.
import React, { useMemo } from 'react';
First, import the useMemo hook from React to enable memoization within your component.
const rawData = [{ id: 1, value: 10 }, { id: 2, value: 20 }, { id: 3, value: 30 }];
This is an array of raw data that we will preprocess for use in a chart component.
const ChartComponent = ({ data }) => { 
  // Chart rendering logic here
  return <div>Rendered Chart</div>;
};
A simple chart component that expects prepared data as a prop.
const ParentComponent = () => {
  const preparedData = useMemo(() => {
    return rawData.map(item => ({
      ...item,
      adjustedValue: item.value * 2 // Example transformation
    }));
  }, [rawData]);

  return <ChartComponent data={preparedData} />;
};
In the parent component, use useMemo to prepare or transform the raw data into a format suitable for the chart component. This transformation will only re-run when the rawData changes, ensuring efficient rendering.
export default ParentComponent;
Export the parent component which renders the ChartComponent with transformed data.