React confused me today… for a simple .push() 😅 I was updating an array in state and did this: items.push(newItem) setItems(items) Pretty normal JavaScript, right? But the UI didn’t update. That’s where I got stuck. Then I realized what was actually happening. Arrays in JavaScript are stored by reference. So .push() doesn’t create a new array — it just modifies the existing one. React compared the old state and new state… and saw the same reference. So it thought: “Nothing changed.” 💡 The way I understand it now: Using .push() → same box 📦 Using spread → new box 📦✨ React only reacts when the box changes, not just what’s inside it. So the correct way: setItems(prevItems => [...prevItems, newItem]) Small thing, but it cleared up a lot for me. One more step forward 🚀 #ReactJS #JavaScript #Frontend #LearningInPublic
It proves small things matter🤝
Great insight! 🌟 Understanding state updates is crucial in React. Keep up the learning journey! 🚀
Or you could have used https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat , same principle, different performance metrics.