𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐒𝐭𝐚𝐥𝐞 𝐂𝐥𝐨𝐬𝐮𝐫𝐞 𝐁𝐮𝐠 🚨 Many developers use useEffect daily… but get confused when bugs appear unexpectedly. Question: Why does this code log the wrong value? Example 👇 import React, { useState, useEffect } from "react"; export default function App() { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, []); return ( <> <button onClick={() => setCount(count + 1)}> Count: {count} </> ); } What’s the issue? 🤔 Even after clicking the button, console always logs: 0 Why? Because of stale closure. useEffect runs only once (empty dependency array []) and the interval callback captures the initial value of count (0). So it never sees updated state. Correct solution ✅ useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, [count]); Best practice ⭐ Use useRef to always get latest value without re-running effect import React, { useState, useEffect, useRef } from "react"; export default function App() { const [count, setCount] = useState(0); const countRef = useRef(count); useEffect(() => { countRef.current = count; }, [count]); useEffect(() => { const id = setInterval(() => { console.log(countRef.current); }, 1000); return () => clearInterval(id); }, []); return ( <> <button onClick={() => setCount(count + 1)}> Count: {count} </> ); } Tip for Interview ⚠️ Always be careful with dependency arrays in useEffect. Wrong dependencies can lead to stale data bugs. Good developers fix bugs. Great developers understand why they happen. #ReactJS #useEffect #JavaScript #Closures #FrontendDeveloper #WebDevelopment #ReactInterview #CodingInterview #ReactHooks
React useEffect Stale Closure Bug Fix
More Relevant Posts
-
🧠 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
-
𝗥𝗲𝗮𝗰𝘁 𝘃𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗪𝗵𝘆 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝗣𝗿𝗲𝗳𝗲𝗿 𝗥𝗲𝗮𝗰𝘁 𝗳𝗼𝗿 𝗨𝗜 𝗣𝗿𝗼𝗷𝗲𝗰𝘁𝘀 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
-
𝗥𝗲𝗮𝗰𝘁 𝘃𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗪𝗵𝘆 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝗣𝗿𝗲𝗳𝗲𝗿 𝗥𝗲𝗮𝗰𝘁 𝗳𝗼𝗿 𝗨𝗜 𝗣𝗿𝗼𝗷𝗲𝗰𝘁𝘀 You built a calculator or to-do app. It felt harder in plain JavaScript. It felt easier in React. This confuses many developers. React is built on JavaScript. So how can it be easier? Here is the simple truth. JavaScript means you control everything. You select each button. You add event listeners. You store values. You update the display. You handle all edge cases. You do two jobs. You handle calculations. You handle the user interface. This makes it complex. React changes the approach. You describe what you want. React handles the rest. For a calculator: You create components. You store values in state. You update state on click. React updates the user interface. You focus on your data. React does the rest. Why React feels easier? - Components organize your code. You break the app into parts. Display, buttons, logic. Each part has one job. In JavaScript, code mixes together. - State manages your data. State holds changing values. Current number, operator, result. When state changes, UI updates. You do not update the UI yourself. - No manual DOM work. JavaScript: document.getElementById('display') React: update state only. React updates the UI. This saves time. - Reuse components easily. Write a button once. Use it everywhere. <Button value="1" /> <Button value="2" /> Same component, different values. - React scales for big apps. Small apps work with plain JavaScript. Large apps need structure. E-commerce, dashboards, chat apps. React keeps code organized. For tiny projects, plain JavaScript is fine. For larger user interface projects, React helps. It reduces your manual work. It prevents common errors. It grows with your project. Source: https://lnkd.in/gqedqJpf
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝘀 𝘀𝗶𝗻𝗴𝗹𝗲-𝘁𝗵𝗿𝗲𝗮𝗱𝗲𝗱. 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
To view or add a comment, sign in
-
-
#js #18 **Spread and Rest Operator** Spread (...) and Rest (...) look the same in JavaScript, but they do opposite jobs depending on where you use them. 🔹 1. Spread Operator (...) 👉 Expands (unpacks) elements Used when you want to take values out of an array/object ✅ Examples 📌 Array Spread const arr1 = [1, 2, 3];const arr2 = [...arr1, 4, 5];console.log(arr2); // [1, 2, 3, 4, 5] 📌 Copy Array (Important ⚠️) const original = [1, 2, 3]; const copy = [...original]; copy.push(4); console.log(original); // [1, 2, 3] console.log(copy); // [1, 2, 3, 4] 👉 Avoids reference issues (unlike direct assignment) 📌 Merge Arrays const a = [1, 2]; const b = [3, 4]; const merged = [...a, ...b]; 📌 Object Spread const user = { name: "Navnath", age: 28 }; const updated = { ...user, city: "Nagpur" }; 📌 Function Arguments const nums = [1, 2, 3]; function sum(a, b, c) { return a + b + c;} sum(...nums); // 6 🔹 2. Rest Operator (...) 👉 Collects (packs) elements into one Used when you want to gather multiple values into a single variable ✅ Examples 📌 Function Parameters function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0);} sum(1, 2, 3, 4); // 10 👉 numbers becomes an array 📌 Array Destructuring const arr = [1, 2, 3, 4]; const [first, ...rest] = arr; console.log(first); // 1 console.log(rest); // [2, 3, 4] 📌 Object Destructuring const user = { name: "Navnath", age: 28, city: "Nagpur"}; const { name, ...others } = user; console.log(name); // Navnath console.log(others); // { age: 28, city: "Nagpur" } key difference: | Feature | Spread (`...`) | Rest (`...`) | | ---------- | ---------------- | --------------- | | Purpose | Expand values | Collect values | | Usage side | Right side (RHS) | Left side (LHS) | | Example | `[...arr]` | `[a, ...rest]` | 🧠 Easy Way to Remember Spread → “Break it” (expand) Rest → “Collect it” (gather) ⚠️ Common Mistake const obj = { a: 1, b: 2 }; const newObj = { ...obj, a: 10 }; 👉 Output: { a: 10, b: 2 } ✔️ Last value overrides previous ones #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
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
-
-
#js #15 **This Keyword** In JavaScript, the this keyword refers to the context in which a function is executed—basically, “who is calling this function.” But unlike many other languages, this in JavaScript is dynamic (it changes depending on how the function is called, not where it’s written). 🔹 1. Global Context In the global scope: console.log(this); In browsers → window In Node.js → global (or {} in strict modules) 🔹 2. Inside an Object Method When used inside an object: const person = { name: "Alice", greet() { console.log(this.name); } }; person.greet(); // Alice 👉 this refers to the object calling the method (person). 🔹 3. Inside a Regular Function function show() { console.log(this); } show(); Non-strict mode → window Strict mode → undefined 🔹 4. Arrow Functions (Important ⚠️) Arrow functions do NOT have their own this. They inherit it from the surrounding (lexical) scope. const obj = { name: "Bob", greet: () => { console.log(this.name); } }; obj.greet(); // undefined 👉 Here, this is NOT obj, it’s from the outer scope. 🔹 5. Event Handlers button.addEventListener("click", function () { console.log(this); // the button }); 👉 this refers to the element that triggered the event 🔹 6. Constructor Functions / Classes function Person(name) { this.name = name; } const p = new Person("John"); console.log(p.name); // John 👉 this refers to the newly created object 🔹 7. Explicit Binding (call, apply, bind) You can manually set this: function greet() { console.log(this.name); } const user = { name: "Emma" }; greet.call(user); // Emma Summary: | Situation | `this` refers to | | ------------------- | --------------------------- | | Global scope | Global object | | Object method | The object | | Regular function | Global / undefined (strict) | | Arrow function | Lexical (outer) `this` | | Constructor (`new`) | New instance | | Event handler | Element triggering event | | `call/apply/bind` | Explicitly set value | #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
JSInterop in Blazor: Is your C#-to-JS bridge suffocating your app? How I vet my JavaScript integrations: ❌ Junior You: The "Chatty Bridge" Trap Request: "We need to render 5,000 coordinates on a JavaScript map interface." Action: Loop through the C# list and send them to JS one by one. #csharp foreach (var coordinate in treeCoordinates) { await JS.InvokeVoidAsync("map.addMarker", coordinate); } The Cost: The C#-to-JS boundary is crossed 5,000 individual times. On Blazor Server, each call is a SignalR round trip. On WASM, each call is a shared memory boundary crossing. The cumulative synchronization overhead freezes the UI thread. The browser gasps for air. You Now: The "Batched Payload" Fix Request: "We need to render 5,000 coordinates on a JavaScript map interface." Action: "Can we package this and cross the bridge exactly once?" #csharp // Cross the boundary once with the entire payload await JS.InvokeVoidAsync("map.addMarkersBatched", treeCoordinatesArray); #javascript // The JS side must handle bulk insertion efficiently too window.map = { addMarkersBatched: function (coordinates) { // Batch DOM operations in one pass; don't loop and mutate individually const markers = coordinates.map(c => createMarker(c.lat, c.lng)); markerLayer.addLayers(markers); } } Important: Batching on the C# side moves the bottleneck, it doesn't eliminate it. If your JS function loops through 5,000 coordinates and mutates the DOM individually, you've just shifted the freeze from the bridge to the browser's render thread. The JS side needs to handle bulk insertion in a single pass. What you gain: →Responsive UI: The boundary crossing overhead drops from 5,000 hits to one; the UI thread stays free. →Server-friendly: On Blazor Server, you go from 5,000 SignalR round trips to one. Your infrastructure will thank you. →Scalable pattern: The same approach applies to any bulk operation across the interop boundary; chart data, table rows, canvas drawing instructions. Treat the Blazor-to-JS bridge like a toll road. Don't pay the toll for every single passenger; put them all in a bus. 💾 Save this for your next map, chart, or data-heavy JS integration. Have you ever frozen a browser tab pushing data to a JS library one record at a time? #Blazor #DotNet #JSInterop #WebPerformance #CleanCode
To view or add a comment, sign in
-
-
🚀 Fetch vs Axios in JavaScript When building modern web applications, interacting with APIs is a daily task. Two of the most commonly used tools for this are Fetch and Axios. 🔹 What is fetch()? Definition: fetch() is a built-in Web API in JavaScript used to make HTTP requests to servers and retrieve resources. 👉 It is promise-based and available in all modern browsers. 📌 How Fetch Works >> Sends a request to a server (GET, POST, etc.) >> Returns a Promise >> Resolves to a Response object >> You must extract data manually (e.g., .json()) 💻 Example async function fetchData() { try { const response = await fetch("https://lnkd.in/dQeGAVaB"); // Checking response status manually if (!response.ok) { throw new Error("HTTP error! Status: " + response.status); } // Convert response into JSON const data = await response.json(); console.log(data); } catch (error) { console.error("Fetch Error:", error); } } ⚠️ Important Characteristics of Fetch ✔️ Built into browser (no installation) ✔️ Returns Promise ✔️ Requires manual JSON parsing ✔️ Does NOT throw errors for HTTP failures (you must handle it) ✔️ Slightly more verbose 🔹 What is axios? Definition: axios is a third-party JavaScript library used to make HTTP requests from the browser or Node.js. 👉 It is also promise-based but provides many additional features out of the box. 📌 How Axios Works >> Sends HTTP requests (GET, POST, PUT, DELETE, etc.) >> Automatically transforms response into JSON >> Automatically throws errors for bad status codes >> Provides advanced configuration options 💻 Example import axios from "axios"; async function fetchData() { try { const response = await axios.get("https://lnkd.in/dQeGAVaB"); // Axios directly gives data console.log(response.data); } catch (error) { console.error("Axios Error:", error); } } ⚠️ Important Characteristics of Axios ✔️ Requires installation (npm install axios) ✔️ Automatic JSON transformation ✔️ Better error handling ✔️ Supports interceptors (modify request/response globally) ✔️ Supports timeout, cancellation, headers easily ✔️ Cleaner and shorter syntax 💡 When to Use Fetch vs Axios? 👉 Use Fetch when: >> You want a lightweight solution >> No external dependencies required >> Working on small/simple projects 👉 Use Axios when: >> You are building real-world applications >> Need better error handling >> Want features like: >>Interceptors, Global configuration, Request cancellation #JavaScript #WebDevelopment #Axios #FetchAPI #Frontend #Programming #Developers #Coding
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
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