🚀 Day 14 – setTimeout Gotcha Think setTimeout runs exactly after the delay? Not quite. 😏 Here’s a classic trap 👇 for (var i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } 👉 What do you expect? 1 2 3 ❌ 👉 What you get: 4 4 4 😲 💥 Why this happens var is function scoped, not block scoped By the time setTimeout executes, the loop is already done i becomes 4, so all callbacks log the same value ✅ Fix #1: Use let for (let i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔️ Output: 1 2 3 ✅ Fix #2: Use Closure for (var i = 1; i <= 3; i++) { ((j) => { setTimeout(() => { console.log(j); }, 1000); })(i); } ✔️ Output: 1 2 3 🧠 Pro Insight (Angular Devs 👇) This matters a LOT when dealing with: async API calls loops with delayed UI updates timers inside components Using let or closures prevents unexpected UI bugs 🐛 ⚡ Takeaway 👉 setTimeout doesn’t pause your loop 👉 It schedules a callback for later 👉 Scope matters more than delay 💬 Have you ever been bitten by this bug? #JavaScript #Angular #WebDevelopment #AsyncJS #Frontend #100DaysOfCode
Nikhil PC’s Post
More Relevant Posts
-
We started naming our useEffect functions some time ago. Tiny change. Outsized impact. ❌ The "Mystery" Way useEffect(() => { fetch(`/api/users/${userId}`) .then(res => res.json()) .then(setUser); }, [userId]); Four effects like this in a component? You're reading every line just to understand what's happening. ✅ The "Self-Documenting" Way useEffect(function fetchUserProfile() { fetch(`/api/users/${userId}`) .then(res => res.json()) .then(setUser); }, [userId]); Now the name tells the story. You only open it when something breaks. But the real wins were unexpected: → If you can't name it without "and" — split it. "fetchUserAndLoadPermissions" is two effects in a trench coat. → Vague names expose effects that shouldn't exist. "updateStateBasedOnOtherState" isn't an effect. It's derived state. Move it out. → Stack traces go from useless to useful. "at (anonymous)" → no idea. "at fetchUserProfile" → straight to the bug. Want to enforce it across your team? "prefer-arrow-callback": ["error", { "allowNamedFunctions": true }] Zero new libraries. Zero new patterns. Just a name. So, start naming your effects. #React #JavaScript #FrontendDevelopment #WebDev
To view or add a comment, sign in
-
-
Your useEffect is firing 6 times. It's probably not what's in the dependency array. I had [options] in mine. One dependency. Looked fine. The effect ran on every single render anyway — hammering my API with duplicate calls I couldn't explain. The problem wasn't the value. It was the reference. options was an object getting recreated fresh on every render, so React saw a "new" dependency every time — even when the actual data hadn't changed. React doesn't deep-compare objects in the dep array. It checks identity. Fix was wrapping options in useMemo. Two lines. Effect ran once. Done. But honestly, the bigger shift was realising I'd been thinking about dependencies wrong. It's not just what is in the array — it's whether the things in the array are actually stable between renders. If your effect fires more than it should, check the stability of your deps, not just the list. What kills you about useEffect? Curious if this one's common. #react #javascript #reacthooks #frontenddevelopment #webdev
To view or add a comment, sign in
-
-
I was building a UI recently and something felt off. I added a console.log out of habit. Clicked a button once. Watched the same API call fire 10 to 11 times in a row. One click. Ten requests. I knew React re-renders components when state changes. What I didn't fully appreciate was how easy it is to accidentally create a chain reaction. A state update triggers a render, something inside that render looks "new" to React even when it isn't, and suddenly your useEffect is firing over and over. The fix came down to being more precise: stabilising object references with useMemo, wrapping functions in useCallback, and being honest about what my useEffect actually needed to watch. After fixing it: one click, one API call. It sounds obvious in hindsight. It always does. If you've hit this before, how did you catch it? Console.log is how I found mine. I'm told the React DevTools Profiler is better. That's what I'm learning next. React developers, how do you debug unexpected re-renders in production? #React #Frontend #FrontendDevelopment #ReactJS #WebDevelopment #JavaScript #SoftwareEngineering
To view or add a comment, sign in
-
-
Mistake #1: I used useEffect for almost everything. Fetching data, syncing props to state, deriving values, even handling basic logic. At one point, my components had more useEffect than actual UI. Things worked… but they were fragile. Small changes broke unexpected parts. The realisation came later: useEffect is meant for side effects, not general logic. If you’re calculating something from props or state, you probably don’t need an effect at all. Once I reduced unnecessary useEffect usage, my components became predictable and easier to debug. Follow for Day 2. Repost if you’ve ever been stuck debugging useEffect. #reactjs #frontend #javascript #webdevelopment #cleanCode #softwareengineering
To view or add a comment, sign in
-
-
✅ Assignment-6 — 60/60 Project: DevTools— Digital Workflow Platform (Basic React Project) 🔧 Features: → Product cards — 3-column responsive layout → Add to cart with live navbar count update → Remove items + proceed to checkout → Toast notifications via React-Toastify → Product ↔ Cart toggle → Fully responsive ⚙️ Tech: React.js • Tailwind CSS • DaisyUI • React-Toastify • JSON Part of my ongoing journey at Programming Hero under the guidance of Jhankar Mahbub. 🔗 Live link & GitHub repo in the comments. #React #JavaScript #WebDevelopment #Frontend #TailwindCSS #ProgrammingHero #OpenSource
To view or add a comment, sign in
-
Day 9 - Frontend Diaries 👉 I thought props are just for passing data While working with components, my understanding of props was simple pass data from parent to child and use it inside the component That’s it But while building more components, I started noticing something Whenever props change, the component re-renders Even small changes in props can affect how a component behaves It’s not just about passing values it’s about controlling the component Props define what a component receives and how it reacts to changes That’s when I realized Props are not just data they are what drive component behavior #frontenddevelopment #reactjs #webdevelopment #fullstackdeveloper #softwareengineering #buildinpublic #developers
To view or add a comment, sign in
-
I built a Pomodoro timer into ACE and honestly it's been one of those features I didn't know I needed until I had it. The idea was simple. I was using ACE to study and kept switching tabs to find a timer. So I just built one in. 25 minutes. Focus. Break. Repeat. If you're building something, don't sleep on the small features. Sometimes the thing that makes your product actually usable isn't the AI or the fancy architecture. It's the 25 minute timer sitting quietly in the corner. #buildinpublic #nextjs #webdevelopment #javascript #frontenddevelopment
To view or add a comment, sign in
-
setTimeout(fn, 0) looks simple. Until a Promise shows up… and breaks your expectations. You write this: setTimeout(() => console.log("timeout"), 0); Promise.resolve().then(() => console.log("promise")); And you think: “Timeout has 0 delay… it should run first.” But the output is: ->promise ->timeout So what’s actually happening? Not magic. Not randomness. Just how JavaScript is designed. When your code runs, this is the order: Run all synchronous code Execute all Promises (microtasks) Then execute setTimeout (macrotasks) Now read that again. 👉 Promises are not faster 👉 They are just scheduled differently Here’s the hidden detail most devs miss: Even if your setTimeout is ready… JavaScript will pause it until every single Promise is finished. So in reality: setTimeout(fn, 0) → “Run me later” Promise.then() → “Run me right after this code” That’s why Promises always win. Not because they’re special… But because the event loop always clears microtasks first. The simple mental model: 👉 sync → promises → timers Once you understand this, you stop guessing async behavior… …and start predicting it. #javascript #webdev #eventloop #programming #promises #settimeout #nodejs #javascript #nestjs #backend #softwareengineering
To view or add a comment, sign in
-
-
⚛️ Old vs New: Handling Loading States the Smarter Way ❌ Before React 19, managing loading states meant dealing with isLoading flags, conditional renders, and custom spinners everywhere. Too much boilerplate… for something we use all the time. ✅ With React 19, the new <Loading /> component changes everything. It works hand-in-hand with Suspense to handle async UI automatically while your components fetch data. ✨ Key Features: 🔄 Automatic Loading State Handling — No more manual flags ⚙️ Built-in with Suspense — Seamless integration with async components 🎨 Customizable UI — Swap <Loading /> with your own spinner or skeleton 🧠 Cleaner Code, Less Re-renders — More declarative, more efficient #react #webdev #frontend #javascript #reactjs #coding #softwareengineering #devtips #ReactTips
To view or add a comment, sign in
-
-
🧠 Day 24 — Optional Chaining (?.) & Nullish Coalescing (??) Tired of errors like “Cannot read property of undefined”? 🤔 These two operators will save you 🚀 --- ⚡ 1. Optional Chaining ?. 👉 Safely access nested properties const user = { profile: { name: "John" } }; console.log(user.profile?.name); // John console.log(user.address?.city); // undefined (no error) 👉 Stops execution if value is null or undefined --- ⚡ 2. Nullish Coalescing ?? 👉 Provides a default value only if value is null or undefined const name = null; console.log(name ?? "Guest"); // Guest --- ⚠️ Difference from || console.log(0 || "Default"); // "Default" ❌ console.log(0 ?? "Default"); // 0 ✅ 👉 || treats falsy values (0, "", false) as false 👉 ?? only checks null or undefined --- 🚀 Why it matters ✔ Prevents runtime errors ✔ Cleaner and safer code ✔ Widely used in APIs & React apps --- 💡 One-line takeaway: 👉 “Use ?. to safely access, ?? to safely default.” --- Once you start using these, your code becomes much more robust. #JavaScript #ES6 #OptionalChaining #WebDevelopment #Frontend #100DaysOfCode 🚀
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