I'm currently playing around with the state by trying to update it. I came across two solutions to achieve my update as you can see from my 2 Examples.
I was wondering if there are any major differences between these two approaches ?
Because in the End you always ending up, updating the State. But I'm also curious from a performance / architecture point of view.
While I think the first Example is cleaner and clearer to understand then the second one, I don't really know if the "cleaner" aspect is really true.
Example 1
const handleTableRowEdit = (row) => {
// Get current Items State
// Spread all elements from array into new array.
const existingItems = [...items];
// Add new Property to passed row object
const newRow = { ...row, isEditing: true };
// Find Array Index from passed row
const findIndex = items.findIndex((x) => x.id === newRow.id);
// Update Array with new Row at index position
existingItems[findIndex] = { ...newRow };
// Set State to updated Array.
setItems(existingItems);
};
Difference Highlighting
...
// Spread all elements from array into new array.
const existingItems = [...items];
...
// Set State to updated Array.
setItems(existingItems);
Example 2
const handleTableRowEdit = (row) => {
// Get current Items State
// Set reference to existing items Array.
const existingItems = items;
// Add new Property to passed row object
const newRow = { ...row, isEditing: true };
// Find Array Index from passed row
const findIndex = items.findIndex((x) => x.id === newRow.id);
// Update Array with new Row at index position
existingItems[findIndex] = { ...newRow };
// Set State to updated Array.
// Set new State by spreading all elements of existing array into a new array.
setItems([...existingItems]);
};
Difference Highlighting
...
// Set reference to existing items Array.
const existingItems = items;
...
// Set new State by spreading all elements of existing array into
a new array.
setItems([...existingItems]);