Junior
// mutates the current state -> setPhotos([...photos, photo]); // does not see the change // mutates the variable // no key
sobes.tech AI
Answer from AI
In React, it is important not to mutate the current state directly, but to create a new object or array so that React can detect changes and update the component.
For example, if you have an array called photos in the state, the correct way to update it is:
setPhotos([...photos, photo]);
This creates a new array with the added element, and React will see the change.
If you mutate the variable directly, for example by doing photos.push(photo), React will not detect the change, and the UI will not update.
It is also important to specify a unique key for list elements during rendering, so React can efficiently track changes:
{photos.map(photo => (
<img key={photo.id} src={photo.url} alt="photo" />
))}
Without a key, React may incorrectly update list items.