React sort() Mutates Original Array, Causes UI Error

🟨 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗗𝗮𝘆 𝟱𝟰: 𝗧𝗵𝗲 .sort() 𝗠𝘂𝘁𝗮𝘁𝗶𝗼𝗻 𝗧𝗿𝗮𝗽 (𝗥𝗲𝗮𝗰𝘁 𝗦𝘁𝗮𝘁𝗲 𝗕𝘂𝗴) In JavaScript, .sort() looks harmless — but in React apps it can break your UI with a confusing error. 🔹 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗜 𝗙𝗮𝗰𝗲𝗱 While rendering a list, I sorted the data directly before mapping. Everything worked… until this error appeared: ❌ 𝘊𝘢𝘯𝘯𝘰𝘵 𝘢𝘴𝘴𝘪𝘨𝘯 𝘵𝘰 𝘳𝘦𝘢𝘥 𝘰𝘯𝘭𝘺 𝘱𝘳𝘰𝘱𝘦𝘳𝘵𝘺 '0' 𝘰𝘧 𝘰𝘣𝘫𝘦𝘤𝘵 '[𝘰𝘣𝘫𝘦𝘤𝘵 𝘈𝘳𝘳𝘢𝘺]' 🔹 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗛𝗮𝗽𝗽𝗲𝗻𝘀 .sort() mutates the original array. In React: • State and props are treated as immutable • Libraries like Redux / React Query may freeze data • Mutating them directly can cause runtime errors 🔹 𝗧𝗵𝗲 𝗕𝘂𝗴 𝘵𝘳𝘢𝘯𝘴𝘢𝘤𝘵𝘪𝘰𝘯𝘴.𝘴𝘰𝘳𝘵((𝘢, 𝘣) => 𝘯𝘦𝘸 𝘋𝘢𝘵𝘦(𝘣.𝘥𝘢𝘵𝘦) - 𝘯𝘦𝘸 𝘋𝘢𝘵𝘦(𝘢.𝘥𝘢𝘵𝘦)); Here: • transactions came from state/props • .sort() tried to modify it in-place • React blocked the mutation → 💥 error 🔹 𝗧𝗵𝗲 𝗙𝗶𝘅 Always clone before sorting. [...transactions].sort((a, b) => new Date(b.date) - new Date(a.date)); Now: • Original state stays untouched • Sorting happens on a new array • React stays happy ✅ 🔹 𝗠𝘂𝘁𝗮𝘁𝗶𝗻𝗴 𝗠𝗲𝘁𝗵𝗼𝗱𝘀 𝘁𝗼 𝗪𝗮𝘁𝗰𝗵 𝗢𝘂𝘁 𝗙𝗼𝗿 • sort() • reverse() • push() / pop() • splice() 🔹 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 .sort() mutates. React state should not. Immutability in React isn't optional — it's the rule. 💬 GitHub example in the comments. #JavaScript #React #Frontend #100DaysOfCode #Day54

To view or add a comment, sign in

Explore content categories