I am working on a performance-critical section of a stock trading React application that involves a large number of components displaying real-time data.
I'm using React.memo()
with a custom compare function to optimize rendering and avoid unnecessary re-renders. However, I am noticing that the components are still re-rendering more often than expected.
Here's a simplified version of my ExpensiveComponent
:
import React from "react";
const ExpensiveComponent = ({ data, onAction }) => {
// Expensive render logic here
console.log("ExpensiveComponent rendered");
return (
<div>
{/* Render data */}
<button onClick={() => onAction(data.id)}>Perform action</button>
</div>
);
};
const areEqual = (prevProps, nextProps) => {
// Assume data objects have the same reference if they are equal
return prevProps.data === nextProps.data && prevProps.onAction === nextProps.onAction;
};
export default React.memo(ExpensiveComponent, areEqual);
And here's the parent component that renders multiple instances of ExpensiveComponent
:
import { useCallback, useState } from "react";
import ExpensiveComponent from "./ExpensiveComponent";
import dataService from "./dataService";
const ParentComponent = () => {
const [dataList, setDataList] = useState(dataService.getData());
const handleAction = useCallback((id) => {
console.log("Action performed on item with id:", id);
}, []);
return (
<div>
{dataList.map((data) => (
<ExpensiveComponent key={data.id} data={data} onAction={handleAction} />
))}
</div>
);
};
export default ParentComponent;
I expect ExpensiveComponent
instances to only re-render when the data
or onAction
props change. However, when I check the console, I can see that the "ExpensiveComponent rendered" message appears more frequently than expected, indicating unnecessary re-renders.
Am I missing something in my implementation of React.memo
or the custom compare function that might cause these unnecessary re-renders? Any insights from React experts would be greatly appreciated.