Is it possible to apply React.memo to an array of components with a for loop?
Say I have the following three components:
const Item1 = (props) => {
const { index } = props;
return (
<div>{index}</div>
);
}
const Item2 = (props) => {
const { index } = props;
return (
<div>{index}</div>
);
}
const Item3 = (props) => {
const { index } = props;
return (
<div>{index}</div>
);
}
Could I do this in my App component?
const App = (props) => {
const items = [Item1, Item2, Item3];
let itemarray = [];
let index = 0;
for (const item of items) {
const MemoizedItem = React.memo(item);
itemarray.push(<MemoizedItem key={index} index={index} />);
index++;
}
return (
<div>
{itemarray}
</div>
);
}
I know I can hard code React.memo for each of the three items (see below), but I'd like to be able to do it iteratively.
const Item1 = React.memo((props) => {
const { index } = props;
return (
<div>{index}</div>
);
});
//...same for Item2 and Item3