Home > Blockchain >  What's the difference between directly copying an array to another variable and using new_varia
What's the difference between directly copying an array to another variable and using new_varia

Time:10-09

I'm using a React useState variable.

This was my previous code:

const imgList = imagesList;
imgList.splice(deleteImgIndex.current, 1);
setImagesList(imgList);

In the above code, the UI was not rerendering.

This is the new correct working code:

const imgList = [...imagesList];
imgList.splice(deleteImgIndex.current, 1);
setImagesList(imgList);

But this code works correctly and does a rerender of the UI. Why is this happening and what's the actual difference between the two procedures?

CodePudding user response:

In your first example, imgList is a reference to imagesList while in the second it is a copy. If you change one (shallow) element in either array in the first example it will be reflected in both while in the second it will not.

The code works in both examples because slice also makes a copy.

  • Related