Blog>
Snippets

Memoizing Complex Chart Props with React useMemo

Demonstrate how to use React's useMemo hook to memoize complex objects or arrays passed as props to a chart component, preventing unnecessary rerenders when these props haven't changed.
const chartOptions = React.useMemo(() => ({
    responsive: true,
    plugins: [],
}), []);
This code memoizes the chart options object using React's useMemo hook. Because the dependencies array is empty, the object will only be recalculated when the component mounts, preventing unnecessary re-renders.
const MemoizedChartComponent = ({ data, options }) => {
    const memoizedData = React.useMemo(() => data.map(item => expensiveDataTransformation(item)), [data]);
    return <ChartComponent data={memoizedData} options={options} />;
};
Here, useMemo is used to memoize a transformed version of the data prop before passing it to a chart component. The transformation is only run when the data prop changes, optimizing performance.