Home > Mobile >  When I update an array, should I have to copy the array every time?
When I update an array, should I have to copy the array every time?

Time:06-06

const [items, setItems] = useState([]);

const updateItem = (updatedItem) => {
  setItems(items.map((item) => {
    if (item.id === updatedItem.id) return updatedItem;
    return item;
  });
};

For firing re-render, I update an array like the example.

I don't think that's efficient, because when an item needs to be updated, the whole array is copied. If the length of the items is 100,000, for updating an item, it copies all items, right?

Is it inevitable?

For adding an item, I can write code like the following:

const addItem = (newItem) => {
  setItems(items.concat(newItem)); // instead of [...items, newItem]
}

I'm not 100% sure but I think it may be more efficient.

How can I avoid unnecessary work?

CodePudding user response:

The short answer - there is no simple option for that and more - this is not a bottleneck when we are talking bout React performance.

The long answer - React need to know when the data changed. And for the performance reasons, was decided to check the equality of links for the object and arrays. If the links are the same - then no data changed.

Just imagine opposite situation - you have a complex object and you changed one property somewhere deep. Now you need to recursively travers the tree and compare each and every value, including other objects.

However, if you are concerned about performance in React - you should look into re-render optimizations. This is the main reasons for the performance issues.

CodePudding user response:

  1. All comparing functions have to run through all the array, so there is no better optimisation
  2. Having 100000 items in an array can be very bad, if you dont use Virtualized list such as react-window or virtuoso
  • Related