𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝘀 𝘀𝗶𝗻𝗴𝗹𝗲-𝘁𝗵𝗿𝗲𝗮𝗱𝗲𝗱. So how does your UI stay responsive while a fetch() is running? Most devs say "async/await". That's not an answer. That's a keyword. Here's what actually happens. 👇 ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗿𝗮𝗰𝗲 𝗮 𝘀𝗶𝗻𝗴𝗹𝗲 𝗳𝗲𝘁𝗰𝗵() 𝗰𝗮𝗹𝗹 𝘁𝗵𝗿𝗼𝘂𝗴𝗵 𝘁𝗵𝗲 𝗲𝗻𝘁𝗶𝗿𝗲 𝗲𝗻𝗴𝗶𝗻𝗲: 𝗦𝘁𝗲𝗽 𝟭 — fetch() hits the Call Stack. The JS engine sees it, pushes it on the stack. But fetch() is not pure JS — it's a Web API. 𝗦𝘁𝗲𝗽 𝟮 — The Call Stack offloads it to the Web API layer. The network request leaves JavaScript entirely. Your browser (or Node.js libuv) handles it in a separate thread. The Call Stack is now FREE. UI stays responsive. 𝗦𝘁𝗲𝗽 𝟯 — Response arrives. Callback enters the Task Queue. The Web API layer puts your .then() or await callback into the appropriate queue and waits. 𝗦𝘁𝗲𝗽 𝟰 — The Event Loop checks both queues. Microtask Queue first (Promise.then, MutationObserver). Drain it completely. Then take ONE callback from the Task Queue. 𝗦𝘁𝗲𝗽 𝟱 — Callback pushed onto the Call Stack. Executed. Your data is now in your component. ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗵𝗲 𝗽𝗮𝗿𝘁 𝗺𝗼𝘀𝘁 𝗱𝗲𝘃𝘀 𝗺𝗶𝘀𝘀: "Non-blocking" doesn't mean JavaScript runs in parallel. It means the blocking work is delegated to something that CAN run in parallel — Web APIs, OS threads, libuv. JavaScript itself never leaves the single thread. The illusion of concurrency comes from the queue system. ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗵𝗶𝘀 𝗶𝘀 𝘄𝗵𝘆: → A long synchronous loop BLOCKS your UI (it holds the Call Stack and the Event Loop never runs) → An awaited fetch() does NOT block your UI (it's off the Call Stack within microseconds) → CPU-heavy work should go in a Web Worker (move it off the main thread entirely) ━━━━━━━━━━━━━━━━━━━━━━━ The whiteboard above shows the full flow visually. Save it + this explanation as a pair. 📌 Interview question: "Is JavaScript asynchronous?" Correct answer: No — it's single-threaded and synchronous. Async behavior comes from the runtime environment around it. Drop a 🔥 if this clicked for you today. #JavaScript #FrontendDevelopment #ReactJS #NodeJS #SoftwareEngineering #OpenToWork #ImmediateJoiner
How JavaScript Fetch Stays Responsive
More Relevant Posts
-
❓ What actually happens when you call fetch('/api')? So I sat down and figured it out. Here's what blew my mind 👇 💡 The JS engine itself is TINY. Just two things inside it: 📦 Memory Heap — where your objects live 📚 Call Stack — tracks what function is running That's it. It can't do timers. It can't make network requests. It can't even listen for a click. 🤯 🎭 So who does all the async work? The BROWSER does. Not JavaScript. ⚙️ Web APIs (written in C++) handle the heavy lifting on separate threads: 🌐 fetch — network requests ⏱️ setTimeout — timers 🖥️ DOM — page manipulation 🖱️ Events — clicks, scrolls, keypresses 💾 LocalStorage, Geolocation, WebSockets… When they finish, they drop callbacks into two queues: 🟢 Microtask Queue (HIGH priority) → Promises, await, queueMicrotask 🔴 Callback Queue (LOW priority) → setTimeout, click, fetch response 🔄 Then the Event Loop steps in: 1️⃣ Is the Call Stack empty? 2️⃣ Drain ALL microtasks first 3️⃣ Run ONE macrotask 4️⃣ Let the browser paint 5️⃣ Repeat forever 🎯 This explains SO much: ✅ Why a heavy loop freezes your page (stack never empties) ✅ Why Promise.then() ALWAYS beats setTimeout(fn, 0) ✅ Why async/await isn't magic — it's just microtask syntax ✅ Why single-threaded doesn't mean single-tasking 👨🍳 My favorite mental model: The JS engine is a single chef. Web APIs are robot assistants running errands in the background. The Microtask Queue is the VIP line. The Callback Queue is the regular line. The Event Loop is the maître d' — but only seats people when the chef is free. 💥 The biggest realization: "JavaScript" the language and "JavaScript" the thing running in your browser are two VERY different things. ✨ The language is small. 🌊 The runtime around it is massive. I mapped the whole thing out with diagrams — call stack traces, V8's Ignition/TurboFan pipeline, the full click-to-fetch-to-DOM lifecycle. Dropping it in the comments 👇 👋 What's something you use every day but never really looked under the hood of? #JavaScript #WebDevelopment #Frontend #V8 #EventLoop #CodeNewbie
To view or add a comment, sign in
-
Angular is finally making Fetch API the default. It was long overdue. Let me explain what’s changing and why it matters. 🔍 WHAT ARE FETCH AND XHR? XMLHttpRequest (XHR) has been the backbone of HTTP requests in browsers since the early 2000s. It’s callback-based, imperative, and designed for a different era of JavaScript. Fetch API arrived in 2015 — Promise-based, composable, and built for the modern async/await world we actually live in. Both do the same job. But how they do it is very different. ⚡ KEY DIFFERENCES 𝗘𝗿𝗿𝗼𝗿 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴 XHR fires onerror on failure. Fetch only rejects on network-level errors — a 404 or 500 still resolves. You must check response.ok manually. Easy gotcha. 𝗦𝘁𝗿𝗲𝗮𝗺𝗶𝗻𝗴 Fetch exposes response.body as a ReadableStream. XHR gives you the whole payload or nothing. 𝗨𝗽𝗹𝗼𝗮𝗱 𝗣𝗿𝗼𝗴𝗿𝗲𝘀𝘀 XHR wins here. xhr.upload.onprogress gives you byte-level tracking. Fetch has no upload progress API — still the main reason to keep XHR around for file uploads. 𝗖𝗮𝗻𝗰𝗲𝗹𝗹𝗮𝘁𝗶𝗼𝗻 XHR has xhr.abort(). Fetch uses AbortController — more composable, one controller can cancel multiple requests. 𝗞𝗲𝗲𝗽𝗮𝗹𝗶𝘃𝗲 Fetch supports { keepalive: true } — requests complete even after the page closes. Perfect for analytics. XHR dies on unload. 𝗡𝗼𝗱𝗲.𝗷𝘀 𝗦𝘂𝗽𝗽𝗼𝗿𝘁 This is the big one. XHR is browser-only. Fetch is native in Node.js 18+. 🅰️ WHY ANGULAR 22 MAKES FETCH THE DEFAULT Angular has been investing heavily in SSR and hydration. And here’s the problem XHR creates: it doesn’t exist in Node.js natively. Every Angular SSR setup using XHR needed polyfills or mocks just to run on the server. That’s fragile, adds complexity, and breaks the isomorphic code story. Fetch just works — same API, same code, running on both server and browser. This matters because: → HttpClient’s transfer cache (server fetches data once, browser reuses it during hydration) integrates cleanly with Fetch → Streaming responses open the door for better SSR performance patterns → keepalive enables reliable analytics on unload — something modern apps need → No more polyfill gymnastics for Node environments XHR isn’t gone — you can still scope it per-route where you need upload progress. But Fetch is now the default engine powering HttpClient. #Angular #WebDevelopment #JavaScript #Frontend #SSR #TypeScript #AngularDeveloper
To view or add a comment, sign in
-
#js #19 **Optional Chaining in Javascript** Optional Chaining (?.) in JavaScript is used to safely access nested properties without causing errors if something is null or undefined. 🔹 Why We Need It Without optional chaining: const user = null; console.log(user.name); // ❌ Error: Cannot read property 'name' 👉 This crashes your code. ✅ With Optional Chaining const user = null; console.log(user?.name); // undefined ✅ (no error) 👉 If user is null or undefined, it stops and returns undefined 🔹 Syntax obj?.propertyobj?.[key]obj?.method() ✅ Examples 📌 1. Nested Objects const user = { profile: { name: "Navnath" }}; console.log(user?.profile?.name); // Navnath console.log(user?.address?.city); // undefined 📌 2. Function Calls const user = { greet() { return "Hello"; }}; console.log(user.greet?.()); // Hello console.log(user.sayHi?.()); // undefined (no error) 📌 3. Arrays const arr = [1, 2, 3]; console.log(arr?.[0]); // 1 console.log(arr?.[5]); // undefined 🔥 Real Use Case (Very Common) const response = { data: { user: { name: "Navnath" } }}; const name = response?.data?.user?.name; 👉 Avoids writing multiple checks like: if (response && response.data && response.data.user) ... ⚠️ Important Points ❌ Doesn’t Work on Undeclared Variables console.log(user?.name); // ❌ if user is not defined at all ⚠️ Stops Only on null / undefined const obj = { value: 0 }; console.log(obj?.value); // 0 ✅ (not skipped) 🔥 Combine with Nullish Coalescing (??) const user = {}; const name = user?.name ?? "Guest"; console.log(name); // Guest 🧠 Easy Memory Trick ?. → "If exists, then access" Otherwise → return undefined, don’t crash #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
✅ JavaScript Advanced Concepts You Should Know 🔍💻 These concepts separate beginner JS from production-level code. Understanding them helps with async patterns, memory, and modular apps. 1️⃣ Closures A function that "closes over" variables from its outer scope, maintaining access even after the outer function returns. Useful for data privacy and state management. function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 2️⃣ Promises & Async/Await Promises handle async operations; async/await makes them read like sync code. Essential for APIs, timers, and non-blocking I/O. // Promise chain fetch(url).then(res => res.json()).then(data => console.log(data)).catch(err => console.error(err)); // Async/Await (cleaner) async function getData() { try { const res = await fetch(url); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } 3️⃣ Hoisting Declarations (var, function) are moved to the top of their scope during compilation, but initializations stay put. let/const are block-hoisted but in a "temporal dead zone." console.log(x); // undefined (hoisted, but not initialized) var x = 5; console.log(y); // ReferenceError (temporal dead zone) let y = 10; 4️⃣ The Event Loop JS is single-threaded; the event loop processes the call stack, then microtasks (Promises), then macrotasks (setTimeout). Explains why async code doesn't block. 5️⃣ this Keyword Dynamic binding: refers to the object calling the method. Changes with call site, new, or explicit binding. const obj = { name: "Sam", greet() { console.log(`Hi, I'm ${this.name}`); }, }; obj.greet(); // "Hi, I'm Sam" // In arrow function, this is lexical const arrowGreet = () => console.log(this.name); // undefined in global 6️⃣ Spread & Rest Operators Spread (...) expands iterables; rest collects arguments into arrays. const nums = [1, 2, 3]; const more = [...nums, 4]; // [1, 2, 3, 4] function sum(...args) { return args.reduce((a, b) => a + b, 0); } sum(1, 2, 3); // 6 7️⃣ Destructuring Extract values from arrays/objects into variables. const person = { name: "John", age: 30 }; const { name, age } = person; // name = "John", age = 30 const arr = [1, 2, 3]; const [first, second] = arr; // first = 1, second = 2 8️⃣ Call, Apply, Bind Explicitly set 'this' context. Call/apply invoke immediately; bind returns a new function. function greet() { console.log(`Hi, I'm ${this.name}`); } greet.call({ name: "Tom" }); // "Hi, I'm Tom" const boundGreet = greet.bind({ name: "Alice" }); boundGreet(); // "Hi, I'm Alice" 9️⃣ 💡 Practice these in a Node.js REPL or browser console to see how they interact. 💬 Tap ❤️ if you're learning something new!
To view or add a comment, sign in
-
𝗥𝗲𝗮𝗰𝘁 𝘃𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗪𝗵𝘆 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝗣𝗿𝗲𝗳𝗲𝗿 𝗥𝗲𝗮𝗰𝘁 𝗳𝗼𝗿 𝗨𝗜 𝗣𝗿𝗼𝗷𝗲𝗰𝘁𝘀 Have you built a small app? Maybe a calculator or to-do list. You might see it feels harder in plain JavaScript. But in React, it feels easier. Why? React uses JavaScript. So how is it easier? Let me explain simply. In JavaScript, you control everything. In React, you describe what you want. React handles the rest. Think about building a calculator. With JavaScript, you: - Select buttons with getElementById. - Add event listeners to each button. - Store values like current number and operator. - Update the display yourself. - Handle edge cases like clear and delete. You do two jobs. You handle calculations. You update the screen. This is why it feels complex. With React, you: - Create components like Button and Display. - Store values in state. - Update state on click. - React updates the UI automatically. You only focus on your data. React does the rest. Why does React feel easier? Components give clean structure. In React, Display and Buttons are separate parts. In JavaScript, everything mixes together. State makes data management easy. React uses state for changing values. When state changes, the UI updates. In JavaScript, you update variables and the UI separately. No manual DOM work. In JavaScript, you use document.getElementById. In React, you update state. React updates the UI. This saves effort. Reusability is easy. You can use a Button component many times with different values. For bigger projects, React helps. Small apps are fine with JavaScript. But for e-commerce, dashboards, or chat apps, React keeps things organized. So, for UI projects, many developers prefer React. It simplifies the work. Source: https://lnkd.in/gqedqJpf
To view or add a comment, sign in
-
I used to manipulate objects directly in JavaScript. Until one day, it didn't work. And the errors were almost impossible to trace. Meanwhile JavaScript has built a clean, deliberate API specifically for the job I had been doing messily for a long time. What is Reflect? Reflect is a built-in JavaScript object that provides a set of methods for performing fundamental operations on objects. The same operations you've always done, but in a more controlled, predictable, and reliable way. Reading properties. Setting values. Checking existence. Deleting keys. Reflect does all of this in a clean way. The most important Reflect methods: -> Reflect.get() - reads a property from an object. const user = { name: "Markus" }; Reflect.get(user, "name"); -> "Markus" Same as user.name - but more explicit and safer in dynamic contexts. -> Reflect.set() - sets a property value and returns true or false. const user = { name: "Markus" }; Reflect.set(user, "name", "John"); -> true console.log(user.name); -> "John" Unlike direct assignment - it tells you whether it succeeded by returning true. -> Reflect.has() - checks if a property exists. Reflect.has(user, "name"); -> true Same as the in operator - but cleaner in functional and dynamic code. -> Reflect.deleteProperty() - deletes a property safely. Reflect.deleteProperty(user, "name"); -> true Same as the delete keyword - but returns a boolean instead of throwing silently. -> Reflect.ownKeys() - returns all keys of an object. const user = { name: "Markus", age: 25}; Reflect.ownKeys(user); -> ["name", "age"] Where Reflect truly shines - with Proxy. Reflect and Proxy are natural partners. Inside a Proxy trap, Reflect lets you perform the default operation in a clean way - without rewriting the behaviour from scratch. Example: const proxy = new Proxy(user, { get(target, key) { console.log(`Reading: ${key}`); return Reflect.get(target, key); -> clean default behaviour } }); Reflect doesn't replace what you already know. It refines it. It makes the operations you perform on objects more intentional, consistent, and significantly easier to debug when something goes wrong.
To view or add a comment, sign in
-
-
I inherited a codebase built on Supabase Edge Functions. Here's exactly why I had to move off them when it came time to scale. Edge Functions are Deno-based isolates. That comes with constraints that aren't obvious until you hit them in practice, and they're even less obvious when you're picking up someone else's architectural decisions. 1. Memory ceiling Supabase Edge Functions cap at ~150MB. That sounds fine until you're running DuckDB-WASM (~30MB) inside one, then fetching and processing a file from Storage on top of that. The headroom disappears fast and there's no way to configure it. 2. The Deno runtime is not Node.js Most npm packages assume a Node.js environment. In Deno you're importing via esm.sh, dealing with compatibility shims, and discovering at runtime that a package has Node-specific dependencies that silently break. Every new dependency becomes a research task before it becomes a tool. 3. Long-running processes don't belong in serverless isolates Edge Functions are designed for short, stateless request/response cycles. If you need a persistent DuckDB connection, warm with a file potentially cached between requests, you're fighting the platform. Every invocation starts cold. The connection you carefully initialised is gone. 4. The wrong execution model for the work Serverless billing is per invocation and duration. For analytical workloads that involve fetching large files and running complex queries, that model gets expensive quickly and unpredictably. A persistent Hono service on Fly.io costs a fixed amount per month regardless of query complexity. The replacement: a dedicated Hono service on Fly.io/Railway running via @hono/node-server. Persistent process, persistent DuckDB connection, no memory ceiling, no Deno import gymnastics, predictable cost. The same framework also handles the client-facing API layer with typesafe routes via @hono/zod-openapi and hono/client, so both services speak the same language. The lesson: Edge Functions are excellent for what they're designed for. Lightweight, stateless, globally distributed request handling. The moment you need persistent state, heavy compute, or memory-intensive workloads, you've outgrown the model. When you inherit a codebase, you inherit its tradeoffs too. The original choice made sense at the time. Recognising when it stops making sense is the job. Supabase itself is not the problem. The Edge Function runtime just isn't the right tool for every job. #webdevelopment #softwarearchitecture #typescript #hono #buildinpublic
To view or add a comment, sign in
-
𝗥𝗲𝗮𝗰𝘁 𝗶𝗻 𝟮𝟬𝟮𝟲: 𝗜𝘁’𝘀 𝗡𝗼𝘁 𝗝𝘂𝘀𝘁 𝗮 𝗟𝗶𝗯𝗿𝗮𝗿𝘆 𝗔𝗻𝘆𝗺𝗼𝗿𝗲 React has evolved and so should the way we think about it. In 2026, React is no longer just about components, hooks, and state. It’s a full ecosystem designed for building high-performance, scalable, production-grade applications. If you're still treating React as a purely client-side library, you're already falling behind. 𝗪𝗵𝗮𝘁’𝘀 𝗖𝗵𝗮𝗻𝗴𝗲𝗱 (𝟮𝟬𝟮𝟰 → 𝟮𝟬𝟮𝟲) React has shifted to a server-first architecture: ✔ Server Components (RSC) — Default rendering on the server → smaller bundles, faster apps ✔ Server Actions — Backend logic directly inside components ✔ Streaming & Suspense — Instant, progressive UI loading ✔ Concurrent Rendering (Stable) — Smarter, smoother UI updates ✔ React Compiler (Emerging) — Automatic performance optimizations 𝗧𝗵𝗲 𝗿𝗲𝗮𝗹𝗶𝘁𝘆: Fully client-heavy React apps are no longer the standard. 𝗧𝗵𝗲 𝗠𝗼𝗱𝗲𝗿𝗻 𝗥𝗲𝗮𝗰𝘁 𝗦𝘁𝗮𝗰𝗸 React alone isn’t enough anymore. A production-ready setup looks like: • Next.js (App Router + RSC) • TypeScript (non-negotiable) • Tailwind CSS • Server Actions / React Query • Edge deployments (Vercel, etc.) • Lightweight state management (Zustand) Overengineering with Redux for every project? That mindset is outdated. 𝗧𝗵𝗲 𝗥𝗲𝗮𝗹 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗥𝗼𝗮𝗱𝗺𝗮𝗽 𝗙𝗼𝘂𝗻𝗱𝗮𝘁𝗶𝗼𝗻𝘀 HTML, CSS, JavaScript (ES6+), async patterns 𝗖𝗼𝗿𝗲 𝗥𝗲𝗮𝗰𝘁 Components, props, hooks, forms 𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗥𝗲𝗮𝗰𝘁 Custom hooks, Context API, performance, error boundaries 𝗠𝗼𝗱𝗲𝗿𝗻 𝗥𝗲𝗮𝗰𝘁 (𝗖𝗿𝗶𝘁𝗶𝗰𝗮𝗹) Server Components, Suspense, Server Actions, Next.js routing 𝗘𝗰𝗼𝘀𝘆𝘀𝘁𝗲𝗺 TypeScript, APIs, authentication, deployment Most developers stop at hooks. That’s just the beginning in 2026. 𝗕𝗲𝘀𝘁 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝘀 ✔ Prefer server-side data fetching ✔ Keep client components minimal ✔ Avoid unnecessary state ✔ Write clean, reusable components ✔ Prioritize performance from day one Heavy JS bundles = lost users. 𝗛𝗼𝗻𝗲𝘀𝘁 𝗧𝗿𝗮𝗱𝗲-𝗼𝗳𝗳𝘀 𝗣𝗿𝗼𝘀 ✅ Massive ecosystem ✅ High performance (with RSC) ✅ Flexibility at scale 𝗖𝗼𝗻𝘀 ❌ Steep learning curve ❌ Rapid evolution ❌ Increasing dependency on frameworks 👉 React is powerful — but no longer beginner-friendly. 𝗛𝗼𝘄 𝘁𝗼 𝗔𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗚𝗲𝘁 𝗕𝗲𝘁𝘁𝗲𝗿 Skip endless tutorials. ✔ Build real-world projects ✔ Clone production apps ✔ Solve real problems ✔ Focus on architecture over syntax Tutorials don’t make you job-ready. Shipping projects does. 𝗙𝗶𝗻𝗮𝗹 𝗧𝗮𝗸𝗲 React in 2026 is about: → Performance → Server-first thinking → Scalable architecture → Real-world problem solving Adapt — and you stay relevant. Ignore it — and you fall behind. What’s the biggest challenge you're facing with modern React right now?
To view or add a comment, sign in
-
-
POST 1 — The JavaScript Event Loop Is Not What You Think ⚙️ Every JavaScript developer says they understand the event loop. Most of them don't. And that gap is exactly why async bugs are so hard to find and fix. Here's what's actually happening 👇 ───────────────────────── First — JavaScript is single-threaded. Always. One thread. One call stack. One thing running at a time. So how does it handle timers, fetch calls, and user events without freezing? It doesn't. The BROWSER does. And then it reports back. ───────────────────────── The pieces most developers mix up: The Call Stack → where your code actually runs. Functions get pushed in, executed, and popped out. This is the only place code runs. Web APIs → setTimeout, fetch, DOM events. These live OUTSIDE the JS engine — in the browser or Node runtime. They run in separate threads you never manage. The Task Queue (Macrotask Queue) → where callbacks from Web APIs wait to be picked up. setTimeout callbacks land here. The Microtask Queue → where Promise callbacks and queueMicrotask calls wait. This queue has HIGHER priority than the task queue. ───────────────────────── The loop itself: 1. Run everything currently on the call stack until it's empty 2. Drain the ENTIRE microtask queue — every single item, including new ones added during draining 3. Pick ONE task from the task queue 4. Go back to step 1 ───────────────────────── Why this produces bugs nobody expects: Promise.resolve().then() runs before setTimeout(() => {}, 0) — always. Microtasks can starve the task queue if you keep adding new ones during draining. Long synchronous code blocks EVERYTHING — no timers fire, no events respond, no UI updates. ───────────────────────── The practical rule: Never put heavy computation directly on the call stack. Break it up. Use setTimeout to yield back to the event loop. Keep microtask chains short and predictable. ───────────────────────── Did the microtask vs task queue distinction surprise you? Drop a comment below 👇 #JavaScript #WebDevelopment #FrontendDevelopment #Programming #WebPerformance
To view or add a comment, sign in
-
🧠 Why React.memo Sometimes Doesn’t Work You wrap your component: const Child = React.memo(({ data }) => { console.log("Rendered"); return <div>{data}</div>; }); You expect it to not re-render. But it still does. Why? 🔍 The real reason React.memo does shallow comparison. So if you pass this 👇 <Child data={{ value: count }} /> 👉 That object is new on every render Even if count didn’t change. ⚠️ Result React sees: {} !== {} 👉 “Props changed” → re-render happens ✅ Fix Memoize the object: const memoData = useMemo(() => { return { value: count }; }, [count]); <Child data={memoData} /> Now the reference stays stable. 🎯 Real Insight React.memo doesn’t prevent re-renders. It only skips them when props are the same reference. 💥 Senior takeaway Most “optimization” fails because of unstable references, not logic. 🧠 Why React.memo Sometimes Doesn’t Work You wrap your component: const Child = React.memo(({ data }) => { console.log("Rendered"); return <div>{data}</div>; }); You expect it to not re-render. But it still does. Why? 🔍 The real reason React.memo does shallow comparison. So if you pass this 👇 <Child data={{ value: count }} /> 👉 That object is new on every render Even if count didn’t change. ⚠️ Result React sees: {} !== {} 👉 “Props changed” → re-render happens ✅ Fix Memoize the object: const memoData = useMemo(() => { return { value: count }; }, [count]); <Child data={memoData} /> Now the reference stays stable. 🎯 Real Insight React.memo doesn’t prevent re-renders. It only skips them when props are the same reference. 💥 Senior takeaway Most “optimization” fails because of unstable references, not logic. #ReactJS #FrontendDeveloper #JavaScript #WebPerformance #SoftwareEngineering #CodingTips #TechCareers #LearningInPublic
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