If we use useMemo to memoize child components say an array of individual book to prevent re-rendering. Wouldn't it effect the performance of the app by consuming more memory to save the states?
Child-
const Book = ({ item }) => {
return useMemo(() => {
console.log(item.name);
return (
<div>
<p>{item.name}</p>
<p>{item.author.name}</p>
</div>
);
}, [item]);
};
Parent-
const Books = (props) => {
const books = props.data.books.map((item) => {
return <Book key={item.id} item={item} />;
});
return (
<>
<div>
<button
onClick={() => {
console.log("render button");
props.func();
}}
>
Add new
</button>
<div>{books}</div>
</div>
</>
);
};
If the props.data.books array is huge in size then, Wouldn't it effect the performance of the app by consuming more memory to save the states? What is the industry practice? Does facebook use useMemo for a post/story?
CodePudding user response:
React hook useMemo
should be used for preventing expensive re-renders. Your Book
component is very cheap to render, as it basically do nothing but show some data, which already are stored in memory. And Book
component is provided with key
attribute, so there is no problem for React to render many of them, unless you need to show at least thousands of them at once.
Expensive render could mean counting derived data - statistics, graphs etc. If such operations are needed, you may consider using data store instead (like Redux Relect)
There is no sharp line when useMemo
should be used. As you expected, it can do more hurt than good.