JSON.stringify for deep equality checks is one of those habits that silently kills performance. It works. Until it doesn't - and by then, you've already paid the cost a thousand times over in a hot render loop or a high-frequency event handler. The problem is simple: stringify serializes the entire object just to produce a string you immediately throw away. It's allocation-heavy, order-sensitive, and completely unaware of undefined or function values. Here's the pattern I see constantly: if (JSON.stringify(prevState) === JSON.stringify(nextState)) return; Instead, reach for a purpose-built solution: import { equals } from "fast-deep-equal"; if (equals(prevState, nextState)) return; fast-deep-equal benchmarks significantly faster, handles edge cases correctly, and doesn't allocate intermediate strings. For most use cases, it's a drop-in replacement. Practical takeaway - audit any equality check sitting inside a loop, React hook, or event listener. If stringify is there, it's costing you more than you think. Have you profiled stringify-based comparisons in your own codebase and actually measured the impact? #JavaScript #WebPerformance #FrontendDevelopment #ReactJS #WebDev #CodeQuality
Ditch JSON.stringify for faster equality checks with fast-deep-equal
More Relevant Posts
-
Well, JavaScript is the ocean that has many small fishes in terms of libraries, and sometimes we have to take a deep dive into many libraries, and integrating burns you out to the core, doesn't it? For logging out the time and date? year? along with seconds, it surely makes our mind chaotic, so we just need some fresh air at that time in a way to relax. // Using Moment.js (Legacy) const nextWeek = moment().add(7, 'days'); // Using Day.js (Modern-ish pre-Temporal) const nextWeek = dayjs().add(7, 'day'); Intriguingly, the new JS update eases our lives as coders, even in the next generation AI, we lack empathy. Does the code work, or actually logics making a significant difference? So let's get into it, Temporal Temporal is the advanced update to resolve dependencies like Moment.js or some other hectic libraries. It gives you a smart, intelligent way to add days in the current date flow just by using the syntax below to handle complex logics efficiently. // No more library dependencies like Moment.js or Day.js! const today = Temporal.Now.plainDateISO(); const nextWeek = today.add({ days: 7 }); console.log(nextWeek.toString()); // Clean, predictable, and immutable. #vibeCoding #javascript #angular #react #NextJs #TypeScript #frontendDevelopment
To view or add a comment, sign in
-
Day 5 ⚡ Async/Await in JavaScript — The Clean Way to Handle Async Code If you’ve struggled with .then() chains, async/await is your best friend 🚀 --- 🧠 What is async? 👉 Makes a function always return a Promise async function greet(){ return "Hello"; } greet().then(console.log); // Hello --- ⏳ What is await? 👉 Pauses execution until a Promise resolves function delay(){ return new Promise(res => setTimeout(() => res("Done"), 1000)); } async function run(){ const result = await delay(); console.log(result); } --- ⚡ Why use async/await? ✔ Cleaner than .then() chaining ✔ Looks like synchronous code ✔ Easier error handling --- ❌ Sequential vs ⚡ Parallel // ❌ Sequential (slow) const a = await fetchUser(); const b = await fetchPosts(); // ⚡ Parallel (fast) const [a, b] = await Promise.all([ fetchUser(), fetchPosts() ]); --- ⚠️ Error Handling try { const data = await fetchData(); } catch (err) { console.log("Error handled"); } --- 💡 One-line takeaway 👉 async/await = cleaner + readable way to handle Promises #JavaScript #AsyncAwait #WebDevelopment #Frontend #Coding #100DaysOfCode
To view or add a comment, sign in
-
Today, I had a conversation with a friend 3+ years in React who hit a frustrating error: ❌ "React is not defined" His response? "But I'm not even using React. I only wrote JSX." That's when I realised — even experienced developers can have gaps in understanding what happens under the hood. And honestly, in the AI era, these fundamentals matter more than ever. 🔍 So what actually happens when you write JSX? You write this: <div className="hello">Hello World</div> Babel (your build tool) transforms it into: React.createElement("div", { className: "hello" }, "Hello World") That's it. JSX is NOT HTML. It's syntactic sugar that compiles down to React.createElement() calls. And since React.createElement is called behind the scenes — React must be in scope. That's why the old error appeared. (Note: React 17+ introduced a new JSX transform that auto-imports the runtime, so you may not see this anymore — but understanding WHY it existed is gold.) 🏗 The React Build Process (simplified) Your JSX code → Babel transpiles JSX → React.createElement() calls → React builds a Virtual DOM (a JS object tree) → React diffs the new tree vs the old one → Only the changed parts get updated in the real DOM This is why React is fast. Not because it touches the DOM often — but because it's surgical about when and what it touches. --- 💡 Why does this still matter in the AI era? AI tools write your components. AI tools fix your errors. But AI cannot debug what you don't understand. When something breaks at build time, at runtime, or in production — you need to know: → What is Babel doing to my code? → Why is the virtual DOM behaving this way? → What triggered a re-render? Basics are not boring. Basics are your debugging superpower. Don't let AI become a crutch that skips your foundation. Let it be the tool that sits on top of a strong one. 🧱 #ReactJS #JavaScript #WebDevelopment #JSX #FrontendDevelopment #Programming #SoftwareEngineering #100DaysOfCode #TechLearning #BuildInPublic
To view or add a comment, sign in
-
-
𝗟𝗲𝘁’𝘀 𝘁𝗮𝗹𝗸 𝗮 𝗹𝗶𝘁𝘁𝗹𝗲 𝗯𝗶𝘁 𝗮𝗯𝗼𝘂𝘁 𝗡𝗼𝗱𝗲.𝗷𝘀! 𝐓𝐨𝐩𝐢𝐜 𝟏: 𝐓𝐡𝐞 𝐍𝐨𝐝𝐞.𝐣𝐬 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩 It’s a meticulously ordered cycle of 6 steps - and most developers have never seen the part that goes between each one. ⚙️ 𝘛𝘩𝘦 6 𝘚𝘵𝘦𝘱𝘴: 1️⃣ 𝘛𝘪𝘮𝘦𝘳𝘴: Recalls setTimeout / setInterval whose delay has passed 2️⃣ 𝘈𝘸𝘢𝘪𝘵𝘪𝘯𝘨 callbacks: Recalls I/O errors that were rejected from the previous iteration 3️⃣ 𝘗𝘰𝘭𝘭𝘪𝘯𝘨: Retrieves new I/O events. This is where Node.js waits when idle. 4️⃣ 𝘊𝘩𝘦𝘤𝘬: setImmediate callbacks, always after Poll 5️⃣ 𝘊𝘭𝘰𝘴𝘦 𝘊𝘢𝘭𝘭𝘣𝘢𝘤𝘬𝘴: socket.on('close'), cleanup handlers 💠The hidden layer: microtasks Between each step, before the loop progresses, Node.js completely empties the microtask queue. Two subqueues, processed in exact order: ➡️ process.nextTick() callbacks - always first ➡️ Promise resolution callbacks - second This means that microtasks have a higher priority than any step of the Event Loop. 📌 𝘛𝘩𝘦 𝘳𝘶𝘭𝘦𝘴 𝘰𝘧 𝘵𝘩𝘶𝘮𝘣: ➡️ process.nextTick() is fired before Promises, even if Promise resolved first. ➡️ setImmediate() is always fired after I/O callbacks in the same iteration. ➡️ The order of setTimeout(fn, 0) and setImmediate() is not deterministic outside of I/O callbacks. ➡️ Never use nextTick() recursively in production code. The event loop is why Node.js can handle thousands of simultaneous connections on a single thread. Controlling its execution order is the difference between writing asynchronous code and understanding it. #nodejs #javascript #backend #eventloop #softwareengineering #webdevelopment
To view or add a comment, sign in
-
-
Nobody expects to fail these 7 React questions. And then they do. The tricky part? None of them are about some lesser-known API. They test whether you actually understand how React works under the hood. Here's what catches people off guard: 🔴 setState batching — calling setCount(count + 1) three times doesn't give you 3. It gives you 1. Closures are sneaky. 🟡 useRef vs useState — mutating a ref updates the value, but the UI never knows. It just sits there. Stale. 🔵 Stale closures in useEffect — an empty dependency array + setInterval = a timer that's frozen in time. Forever stuck at 1. 🟢 React.memo shallow trap — you wrapped your component in memo, feeling smart. But you're passing a new object literal every render. Memo does nothing. 🟣 useEffect cleanup order — most devs think cleanup only runs on unmount. Wrong. It runs before every single re-render effect. Every. Time. 🟡 Index as key — it works until you sort, filter, or reorder. Then React maps the wrong DOM to the wrong data. Inputs keep stale values. Good luck debugging that. 🔴 State mutation — you pushed to the array and called setState. React compared references. Same ref = no update. Your UI is frozen and you have no idea why. I put all 7 into a carousel with code snippets, wrong answers, correct answers, and explanations. Swipe through and test yourself honestly. The pattern? The questions that trip people up aren't about syntax. They're about understanding how React actually thinks. Save this for your next interview — whether you're giving it or taking it. --- #react #javascript #frontend #interviewprep #webdevelopment #softwareengineering #reactjs
To view or add a comment, sign in
-
JavaScript is easy. Until it isn't. 😅 Every developer has been there. You're confident. Your code looks clean. You hit run. And then: " Cannot read properties of undefined (reading 'map') " The classic JavaScript wall. Here are 7 JavaScript mistakes I see developers make constantly and how to fix them: 1. Not understanding async/await ⚡ → Wrong: | const data = fetch('https://lnkd.in/dMDBzbsK'); console.log(data); // Promise {pending} | → Right: | const data = await fetch('https://lnkd.in/dMDBzbsK'); | 2. Using var instead of let/const → var is function scoped and causes weird bugs → Always use const by default. let when you need to reassign. Never var. 3. == instead of === → 0 == "0" is true in JavaScript 😱 → Always use === for comparisons. Always. 4. Mutating state directly in React → Wrong: user.name = "Shoaib" → Right: setUser({...user, name: "Shoaib"}) 5. Forgetting to handle errors in async functions → Always wrap await calls in try/catch → Silent failures are the hardest bugs to track down 6. Not cleaning up useEffect in React → Memory leaks are real → Always return a cleanup function when subscribing to events 7. Treating arrays and objects as primitives → [] === [] is false in JavaScript → Reference types don't compare like numbers — learn this early JavaScript rewards the developers who understand its quirks. 💡 Which of these caught YOU off guard when you first learned it? 👇 #JavaScript #WebDevelopment #Frontend #FullStackDeveloper #React #Programming #CodingTips #Developer #Tech #Pakistan #LearnToCode #JS #SoftwareEngineering #100DaysOfCode #PakistaniDeveloper
To view or add a comment, sign in
-
-
Day 2: The Secret Life of a Function Call — Global vs. Local Execution Context 🚀 Today, I went deeper into the "Big Box" of JavaScript to understand exactly what happens when we call a function. Using this simple square function as an example, here is the line-by-line magic: 🎭 The Two-Phase Performance Phase 1: Memory Allocation Before a single line of code runs, JavaScript scans everything. n, square2, and square4 are allocated memory and set to undefined. The square function gets its own memory space with the entire function code stored inside. Phase 2: Code Execution Line 1: n is assigned the value 2. Line 6: This is where it gets interesting! A Function Invocation happens. 📦 The "Mini Box": Functional Execution Context When square(n) is called, a New Execution Context is created inside the Global one! Memory Phase: A local variable ans is created (undefined). Code Phase: num becomes 2, ans becomes 4. The Return Statement: This is the exit signal. It returns the value 4 to square2 and destroys the local execution context immediately. 📚 The Call Stack: The Manager of it All How does JS keep track of these nested boxes? The Call Stack. It's a stack (LIFO - Last In, First Out). Bottom of stack: Global Execution Context (GEC). When a function is called, it's pushed onto the stack. When it returns, it's popped off. 💡 Interview Tip: Did you know the Call Stack has many names? It’s also called the Execution Context Stack, Program Stack, Control Stack, Runtime Stack, or Machine Stack. Understanding how the stack grows and shrinks is the key to mastering Recursion and avoiding the dreaded "Stack Overflow"! Drop a "🚀" if you’re also following the Namaste JavaScript series! #JavaScript #WebDevelopment #CallStack #ExecutionContext #ProgrammingLogic #FrontendEngineer #CodingCommunity #JSFundamentals
To view or add a comment, sign in
-
-
🤔 Wait… shouldn’t variables be deleted? How is it possible that a function still remembers a variable…even after the function where it was created has already finished executing? 😳 👉 Sounds impossible, right? 🚀 JavaScript’s one of the most powerful concepts: Closures 🧠 What is a Closure? A closure is created when a function is defined inside another function, and the inner function can access variables from its parent scope — even after the parent function has finished execution. ⚡Shouldn’t variables be deleted? Normally, yes ✅ 👉 Once a function finishes, its local variables are removed from memory (thanks to garbage collection) But closures change the game 👇 👉 If an inner function is still using those variables, JavaScript keeps them alive in memory 🔍 What’s really happening? The inner function “closes over” its parent’s variables 💡 That’s why it’s called a closure Even though the outer function is done… the inner function still has access to its scope 😮 🔐 Why Closures Matter (Real Use Cases) Closures aren’t just theory — they’re used everywhere: 👉 Encapsulation (Private Variables) Keep data hidden from global scope 👉 Debouncing & Throttling Control function execution (very common in React apps) 👉 State management patterns Maintain data across function calls 💡 Real Developer Insight Closures are powerful… but can be tricky 👉They can also hold memory longer than expected 👉 Misuse can lead to memory leaks 🚀 Final Thought: Most developers use closures unknowingly… But great developers understand how and why they work. #JavaScript #FrontendDevelopment #WebDevelopment #Closures #CodingTips #LearnJavaScript #BuildInPublic #100DaysOfCode #LearnInPublic
To view or add a comment, sign in
-
-
What is the difference between shallow copy and deep copy? Copying objects in JavaScript is not always what it seems. A `shallow copy` duplicates only the first level. Nested objects are still shared by reference. A `deep copy` duplicates everything recursively. Why did this happen? - The top-level object was copied - But `address` still points to the same reference To fully isolate data, a deep copy is required. Understanding this is critical when: - Managing state - Avoiding unintended mutations - Debugging shared data issues The behaviour is subtle — but the impact is everywhere. #Frontend #JavaScript #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
Most developers still deep clone objects like this: JSON.parse(JSON.stringify(data)) It works. Until it doesn't. Dates become strings. Functions vanish. undefined disappears silently. Circular references throw an error. There's a native alternative that actually handles these cases — and most developers don't know it exists. One caveat: structuredClone() doesn't clone functions or class instances — it's designed for data, not behavior. But for 90% of real-world cases, that's exactly what you need. Available natively in all modern browsers and Node.js 17+ — no library required. Are you still using JSON tricks for deep cloning? 👇 #JavaScript #WebDevelopment #Frontend #JS #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