I have a component with an array of objects in local state:
const [myState, setState] = useState<SomeObjectType[]>([]);
I can update a single object in that array by making a copy of the entire array and then update the property of the single object I wish to update:
OPTION 1
const state = [...myState];
state[id].description = description;
setState(state);
Or I can use map:
OPTION 2
const newState = talkingPoints.map(el => {
// 👇️ if id equals, update description property
if (el.id === id) {
return {...el, description};
}
// 👇️ otherwise return as is
return el;
});
setData(newState);
Or can I do this (since I am 100% certain the id exists in the array)?
OPTION 3
const handleUpdate = () => {
setState(prevState => ({
...prevState,
prevState[id].description = description
}))
}
For cases where I am not 100% certain I can use map and find it:
OPTION 4
const handleUpdate = () => {
setState(prevState => ({
myState: prevState.myState.map(el => el.id === id ? { ...el, description } : el)
}))
}
What is recommended/best practice? Is Option 1 (fully array copy) faster than using map?