How to update item without recreating the whole list in React

Viewed 547

Basically, from an API request, I have an array containing catalogs with a list of items which can be favorited. I display them using three main React components with hooks:

  • Live which makes the API request, stores the catalogs in state, and display one Catalog at a time
  • Catalog which receives items as a prop and a handleFavorite function and displays a list of Item
  • Item which receives an item as props and the handleFavorite function and displays a like or dislike button

Is there any way I can modify the favorited property of a single item in the Catalog component using hooks? Otherwise, since the catalogues are stored in state in the Live component, does that mean I have to recreate the whole array of catalogues every time I have to update one item in one catalog?

There could be a few thousand items in all catalogs combined so it doesn't seem like a good way to handle that. I also thought about useContext but that doesn't seem to be what it's meant for.

1 Answers

In Catalog component you could use useMemo. I quate from react official web site.

useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.

Read more about useMemo here.

Related