Why setState() doesn't work with mutable arrays in React

I had an argument today on a topic which can be skipped very easily (You don't want to miss reading it) The issue was with understanding the following: ↳ setState() ↳ Mutable & Immutable ↳ Deep and Shallow Copy This looks like an easy concept, but if missed, you will keep scratching your head, or just do vibe coding (which is not recommended) const myInitialState = [ { name: 'name', age: 10 }, { name: 'name1', age: 20 }]; ❌ setState(prevState => prevState.sort((a, b) => a.age - b.age)); ✅ setStatet(prevState => { const sorted = [...prevState]; sorted.sort((a, b) => a.age - b.age)); return sorted; }); Q1. Why does updating the older value doesn't work, and the later works? Q2. Creating a copy via [...prevState] is still a shallow copy, then how does React knows something has changed? Answer 1. The reference matters here. When you change something to the older value, the reference doesn't change, and React thinks, it is still unchanged, hence, no re-render trigger, and no UI updates. Answer 2. Even when you create shallow copy, you are creating a new reference. Creating a new array via "[ ]" → Then shallow copy the items using Spread operator. So the reference of sorted and prevState changes. As soon as React sees that in the return, it triggers re-render, as per "Diffing Algorithm". If you have learnt something new, let your friend learn it too via Repost ♻️ P.S. I have bonus questions in the comment section. Let's check how good do you know React #reactjs #react #javascript #coding #programming #softwareengineering #frontend

  • React UI Update Pictorial Representation

📌 BONUS QUESTIONAIRE (Make sure you explain the WHYs here): 1. How does this work out in react update: const initialState = { name: 'name1', age: 10 }; setState(prevState => { ...prevState, name: 'updatedName' }; 2. If I do the following, what is the final output: const initialState = 0; // Back to back state change trigger setState(prevState => prevState + 1); setstate(prevState => prevState + 2); Looking forward to learning more! Cheers 😊

Like
Reply

Nice breakdown 💡 Sorting mutates the array, so copying first is key. The new array reference triggers a re-render. Also, the objects inside keep the same refs, so avoid mutating them too.

See more comments

To view or add a comment, sign in

Explore content categories