🟨 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗗𝗮𝘆 𝟱𝟰: 𝗧𝗵𝗲 .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
React sort() Mutates Original Array, Causes UI Error
More Relevant Posts
-
🚀 Where to Use Spread (...) and Rest (...) Operators in JavaScript (Real Use Cases) Many developers know spread and rest… But the real question is 👉 Where should you actually use them? 🔹 Spread Operator (...) → “Expand Values” 👉 Use spread when you want to open / copy / merge data 1. Copy Arrays (Avoid Bugs) const arr = [1, 2, 3]; const copy = [...arr]; 👉 Without spread: const copy = arr; // ❌ same reference (danger) 2. Merge Arrays const a = [1, 2]; const b = [3, 4]; const result = [...a, ...b]; 👉 Very common in real apps 3. Update Objects (Immutability – VERY IMPORTANT in React) const user = { name: "Javascript" }; const updatedUser = { ...user, age: 21 }; 👉 Don’t mutate original object 4. Pass Array as Function Arguments const nums = [5, 10, 2]; Math.max(...nums); 5. Clone Objects const newUser = { ...user }; 👉 Used in state updates (React) 🔹 Rest Operator (...) → “Collect Values” 1. Functions with Unlimited Arguments function sum(...numbers) { return numbers.reduce((a, b) => a + b); } 👉 Flexible functions 2. Separate Values from Array const [first, ...rest] = [1, 2, 3, 4]; 👉 Extract first → collect remaining 3. Remove Properties from Object const user = { name: "Javascript", age: 21, city: "Hyd" }; const { name, ...others } = user; 👉 Useful for filtering data 4. Handling API Data const { id, ...userData } = response; 👉 Separate important fields >>>Spread = “Break it apart” >>> Rest = “Bring it together” “Both use ... , how do you differentiate?” It depends on context — >> If it’s expanding values → Spread >> If it’s collecting values → Rest Example: function demo(a, b, ...rest) { console.log(a, b, rest); } const arr = [1, 2, 3, 4]; demo(...arr); #JavaScript #WebDevelopment #Frontend #ReactJS #Coding #Developers #LearnJavaScript #100DaysOfCode
To view or add a comment, sign in
-
Blog 07 of my JS Unlocked series is live! 🚀 Array Methods You Must Know in JavaScript 👇 Arrays store data. But these methods are what make that data actually useful — transform it, filter it, calculate from it. In this one I cover: ✅ push() & pop() — add/remove from the end ✅ shift() & unshift() — add/remove from the front ✅ forEach() — loop through every item cleanly ✅ map() — transform every item into a new array ✅ filter() — keep only what passes the condition ✅ reduce() — combine everything into one value ✅ Visual flowcharts for map, filter & reduce ✅ for loop vs map/filter — side by side comparison Would love your feedback if you read it 🙏 🔗 https://lnkd.in/d26hbMGM Thanks to Hitesh Choudhary Sir, Piyush Garg #JavaScript #WebDevelopment #Hashnode #WebDevCohort2026 #LearningInPublic #Frontend #JS
To view or add a comment, sign in
-
New article from my Signals series. This one focuses on a part that is often glossed over in React discussions: consistency under concurrency. I wrote about: - why tearing happens in React 18 - why external reactive data must go through useSyncExternalStore - how remounts can leave stale subscriptions behind - why startTransition does not lower the priority of signal.set() - how to approach Suspense when signals are your source of truth If you're interested in the boundary between React rendering and fine-grained reactivity, this article may be useful. #React #react #signal #frontend #webdev #WebDevelopment #javascript #typescript
To view or add a comment, sign in
-
🔁 JavaScript Tip: Convert Object → Array Easily! Working with objects in JavaScript? Sometimes you need to transform them into arrays for better handling — especially in loops, UI rendering, or API data processing. Here are 3 powerful methods you should know: ✅ Object.keys() → Get all keys ✅ Object.values() → Get all values ✅ Object.entries() → Get key-value pairs 💡 Example: const zoo = { lion: "🦁", panda: "🐼" }; 👉 "Object.keys(zoo)" → ['lion', 'panda'] 👉 "Object.values(zoo)" → ['🦁', '🐼'] 👉 "Object.entries(zoo)" → [['lion', '🦁'], ['panda', '🐼']] 🚀 These methods are super useful in React, API handling, and data transformations. #JavaScript #WebDevelopment #Frontend #ReactJS #CodingTips #Developers #100DaysOfCode
To view or add a comment, sign in
-
-
Blog 04 of my JS Unlocked series is live! 🚀 Function Declaration vs Function Expression: What's the Difference? 👇 These two look almost the same — but one works before you define it and the other throws an error. That one difference has caused bugs in every developer's life at least once. In this one I cover: ✅ What functions are and why we need them ✅ Declaration vs Expression — side by side ✅ Hoisting explained simply (no jargon) ✅ When to use which in real projects ✅ Hands-on challenge — call both before defining and observe what happens Would love your feedback if you read it 🙏 🔗 https://lnkd.in/d9yFhfah Thanks to Hitesh Choudhary Sir, Piyush Garg #JavaScript #WebDevelopment #Hashnode #WebDevCohort2026 #LearningInPublic #Frontend #JS
To view or add a comment, sign in
-
🚀 Callback Functions in JavaScript — Simple but Tricky! A callback function is a function passed as an argument to another function and executed later. 💡 Basic Example: function greet(name, callback) { console.log("Hi " + name); callback(); } function sayBye() { console.log("Goodbye!"); } greet("User", sayBye); 🧠 Output: Hi User Goodbye! 🔥 Question #1 (Hoisting Surprise): function test(callback) { callback(); } test(function () { console.log(a); var a = 10; }); 🧠 Output: undefined 📌 Reason: var a is hoisted but initialized as undefined. 🔥 Question #2 (Scope Trap): function outer(cb) { let x = 5; cb(); } outer(function () { console.log(x); }); 🧠 Output: ReferenceError: x is not defined 📌 Reason: Callback doesn’t have access to outer scope unless passed. 🔥 Question #3 (Async Behavior): console.log("Start"); setTimeout(function () { console.log("Callback"); }, 0); console.log("End"); 🧠 Output: Start End Callback 📌 Reason: Event loop pushes callback to queue (async behavior). 🔥 Quick Check Question #4: function execute(cb) { return cb(); } function sayHi() { return "Hi!"; } console.log(execute(sayHi)); 🧠 Output: Hi! ⚡ Key Takeaways: ✔ Callbacks are fundamental to async JS ✔ Execution context matters more than syntax #JavaScript #Frontend #WebDevelopment #InterviewPrep #Callbacks
To view or add a comment, sign in
-
🧠 JavaScript is a "Brain" with no "Body." Most developers think console.log, setTimeout, and fetch are part of JavaScript. They aren't. 🤯 Standard JS (ECMAScript) is just a logic engine. It handles variables and loops, but it has no "voice"—it can’t talk to a screen or a network alone. To do anything real, it needs a Host Environment: 🌐 Browsers provide the "limbs" (DOM, Web APIs). ⚙️ Node.js provides the "muscles" (File System, HTTP). I just broke down the "Great JavaScript Identity Crisis" on my blog. Understanding this is the secret to mastering the Event Loop and async performance. Read the full breakdown here: 👇 https://lnkd.in/dSwe-qUb Thanks to Hitesh Choudhary Sir, Piyush Garg, Jay Kadlag #JavaScript #NodeJS #Backend #SoftwareArchitecture #Browser #webapi
To view or add a comment, sign in
-
Does understanding JavaScript internals actually matter in "real life"? 🤔 Yesterday, I got my answer. 😅 I was booking movie tickets with friends. Seats were filling FAST. 🎟️🔥 I hit “Pay Now”... and the app started loading. My instinct? Panic. "Did it hang? Should I click again?" 😰 But I stopped myself. I remembered the Event Loop. While I stared at the spinner, JavaScript was juggling: 💳 The Call Stack processing my click. 🌐 Web APIs handling the payment request in the background. ⚡ The Callback Queue waiting to push the success message back to the UI. Because JS is non-blocking, the UI stayed "alive" even while the data was in transit. If I had clicked again, I might have triggered a double-charge or a race condition. Two seconds later? ✅ Payment Successful. > Sometimes, great engineering is invisible. It’s not just about writing code that works; it’s about understanding why it doesn't break under pressure. Don't just learn the syntax. Learn the engine. 🔁✨ Check out the diagram below notice how the 'Priority Queue' handles the logic while the 'Callback Queue' keeps the UI ready for the next move. That’s the secret sauce! #JavaScript #React #JavaScriptDeveloper #ReactjsDeveloper #Frontenddevelopment #SoftwareEngineering #Fullstackdeveloper
To view or add a comment, sign in
-
-
⚛️ React Performance Tip: Stop Recomputing on Every Render A common mistake in React is recalculating data on every render: ```javascript id="s7dh2k" const processedData = data.map(...); ``` ❌ This runs every time the component re-renders ❌ Leads to unnecessary computation and slower UI Instead, memoize it using `useMemo`: ```javascript id="k39xdl" const processedData = useMemo(() => { return data.map(...); }, [data]); ``` ✅ Runs only when `data` changes ✅ Prevents unnecessary recalculations ✅ Improves performance significantly 💡 Key takeaway: Use `useMemo` when: • Expensive computations • Large datasets • Avoiding repeated work 🚀 Small optimization = big performance boost What’s your go-to React performance trick? #ReactJS #JavaScript #Frontend #Performance #WebDevelopment #Coding
To view or add a comment, sign in
-
-
JavaScript’s Date object has been a source of developer frustration for decades, with complex time zone handling, and zero-indexing months, etc., you name it... Enter Temporal: a modern, immutable, and easy-to-use API for dates and times in JS. 👆 Temporal is the biggest addition to ECMAScript since ES2015 Key highlights: ✅ Immutable by design – No more accidental date changes. ✅ Built-in Time Zone support – First-class handling of time zones and DST. ✅ Clearer Syntax – Distinct objects for PlainDate, ZonedDateTime, and Duration. ✅ Reliable Parsing – Strict ISO 8601 strings only. It is currently a Stage 3 proposal and is the biggest upgrade to JS time management ever. Read more about how it works: 👉 https://lnkd.in/ddJNDRy4 #JavaScript #WebDevelopment #Coding #Frontend #SoftwareEngineering
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
https://github.com/nishchaya2k