The Node.js Event Loop Explained (The Right Way) Here's the complete picture. The Core Truth is: For EVERY phase → Execute ONE macrotask → Execute ALL nextTick() → Execute ALL Promises → Move to next phase Why This Matters The Node.js event loop isn't a simple cycle like in browsers. It has 5 distinct phases, and microtasks run BETWEEN EVERY PHASE, not just once per loop. The 5 Phases: ⏱️ Timers — setTimeout, setInterval callbacks 📋 Pending Callbacks — Deferred I/O callbacks from the previous cycle 🔄 Poll — I/O events, network requests, file operations ✓ Check — setImmediate callbacks 🔚 Close — Socket and stream closures The Microtask Priority Here's the critical part: nextTick() ALWAYS runs before Promise callbacks. For each phase boundary: 1️⃣ process.nextTick() callbacks execute FIRST 2️⃣ Promise.then() callbacks execute SECOND 3️⃣ Then the next macrotask phase begins The Visualization The diagram shows the complete cycle with all phases and how microtasks fit between each one. Notice how every phase is followed by microtasks—this is the key difference from what most developers think. Drop a comment if this cleared it up! And if you've been caught by the I/O starvation bug, share your story 👇 #Node.js #JavaScript #EventLoop #Backend #WebDevelopment
Node.js Event Loop Explained: 5 Phases and Microtask Priority
More Relevant Posts
-
Topic: Stale Closures in React – The Hidden Bug You Don’t See Coming ⚠️ Stale Closures in React – The Bug That Looks Fine… Until It’s Not Your code works. No errors. No warnings. But suddenly… state behaves incorrectly 😐 Welcome to the world of stale closures. 🔹 What is a Stale Closure? When a function captures an old value of state instead of the latest one. 🔹 The Problem const [count, setCount] = useState(0); useEffect(() => { const interval = setInterval(() => { console.log(count); // ❌ always logs old value }, 1000); return () => clearInterval(interval); }, []); 👉 count is stuck at its initial value. 🔹 Why This Happens React closures capture values at render time, not at execution time. 🔹 Solutions ✅ 1. Add dependency useEffect(() => { console.log(count); }, [count]); ✅ 2. Use functional update setCount(prev => prev + 1); ✅ 3. Use useRef for latest value const countRef = useRef(count); countRef.current = count; 💡 Real-World Impact 👉 Timers 👉 WebSockets 👉 Event listeners 👉 Async callbacks 📌 Golden Rule If your logic depends on changing state, make sure it’s not using a stale snapshot. 📸 Daily React tips & visuals: 👉 https://lnkd.in/g7QgUPWX 💬 Have you ever debugged a stale closure issue for hours? 😅 #React #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #ReactHooks #DeveloperLife
To view or add a comment, sign in
-
🧠 React Doesn’t Update State Immediately (Even Inside the Same Function) Most people know state is async. But here’s the part many don’t realize 👇 Example const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); if (count === 0) { console.log("Still zero?"); } } You click the button. Expected: count = 1 But inside that function… 👉 count is still 0 🔍 Why? Because React doesn’t update state inside the current render cycle. It schedules the update and re-renders later. 🧠 The tricky part Even this won’t work: setCount(count + 1); setCount(count + 1); 👉 Final result = +1, not +2 ✅ Correct way setCount(prev => prev + 1); setCount(prev => prev + 1); Now React uses the latest value. 🎯 The Real Insight State inside a function is a snapshot, not a live value. 💥 Why this matters This causes: Unexpected conditions Wrong calculations Confusing bugs #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #CodingTips #LearningInPublic
To view or add a comment, sign in
-
Day 6 — Find Second Largest Number in an Array (JavaScript) Problem Write a function to find the second largest number in an array. Example Input: [10, 5, 8, 20] Output: 10 Approach First find the largest number, then find the largest number smaller than it. Code function secondLargest(arr){ let largest = -Infinity let second = -Infinity for(let i = 0; i < arr.length; i++){ if(arr[i] > largest){ second = largest largest = arr[i] } else if(arr[i] > second && arr[i] !== largest){ second = arr[i] } } return second } console.log(secondLargest([10,5,8,20])) Alternative Approach function secondLargest(arr){ let sorted = [...new Set(arr)].sort((a,b) => b-a) return sorted[1] } What I Learned How to track two maximum values in a single loop. #javascript #frontenddeveloper #codingpractice #webdevelopment
To view or add a comment, sign in
-
-
Stop disabling the exhaustive-deps linter in your React Effects ⚛️. we all did the same dirty hack: // eslint-disable-next-line 👇. It is the most common frustrating scenario in React development: You write a useEffect to connect to a websocket or track an analytics event. Inside that effect, you need to read the current value of a state variable—like a shopping cart count or a UI theme. But the moment you read that state, the React linter screams at you to add it to the dependency array. If you add it, your effect re-runs every time the state changes (destroying your websocket connection!). If you don't add it, your build fails. So, we all did the same dirty hack: // eslint-disable-next-line. React finally solves this permanently with useEffectEvent. ❌ The Legacy Way (eslint-disable): Forces you to break the rules of React. Creates a massive risk for stale closures and hidden bugs. Makes your code harder to maintain and review. ✅ The Modern Way (useEffectEvent): Extracts your "event" logic cleanly out of your "lifecycle" logic! • Always Fresh: It guarantees your callback will always read the absolute latest props and state. • Non-Reactive: It is intentionally ignored by the dependency array. It will never cause your useEffect to re-run. • Clean Code: You can finally turn your linter rules back on and trust your dependencies again. The Shift: We are moving away from fighting the framework and using dedicated primitives to separate reactive synchronization from non-reactive events. #ReactJS #React19 #WebDevelopment #Frontend #JavaScript #CleanCode #SoftwareEngineering #TechTips #WebDev #WebPerf #Tips #DevTips #ReactTips #FrontendDeveloper #DeveloperTips
To view or add a comment, sign in
-
-
🚀 Day 5/30 – State in React One of the most important concepts 🔥 Today I learned: ✅ State stores dynamic data inside a component → It allows components to manage and update their own data ✅ When state changes → React re-renders the UI → React automatically updates only the changed parts (efficient rendering ⚡) ✅ Managed using useState hook → The most commonly used hook in functional components ✅ State updates are asynchronous → React batches updates for better performance 💻 Example: import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); const handleClick = () => { setCount(prev => prev + 1); // safe update }; return ( <div> <h2>Count: {count}</h2> <button onClick={handleClick}>Increment</button> </div> ); } 🔥 Key Takeaway: State is what makes React components interactive, dynamic, and responsive to user actions. #React #State #FrontendDevelopment #JavaScript #WebDev #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
💡 useEffect Dependencies — Small Array, BIG Difference! One hook… three different behaviors — all based on the dependency array 🤯 Understanding this can save you from bugs and unnecessary re-renders! Let’s break it down 👇 🔹 1. No Dependency Array useEffect(() => { console.log("Runs on every render"); }); 👉 Runs after every render 👉 Can cause performance issues if not handled carefully 🔹 2. Empty Dependency Array [] useEffect(() => { console.log("Runs only once"); }, []); 👉 Runs only once (on mount) 👉 Perfect for: API calls Initial setup 🔹 3. With Dependencies [value] useEffect(() => { console.log("Runs when value changes"); }, [value]); 👉 Runs only when specific values change 👉 Best for syncing state, props, or side effects 🔁 Quick Summary No array → Every render [] → Only once [deps] → When dependencies change ⚠️ Common Mistake Forgetting dependencies can lead to: Stale data Unexpected bugs 👉 Always trust (and understand!) the dependency array. 🚀 Final Thought Mastering useEffect dependencies is the key to writing predictable and efficient React code. Once you get this right, everything starts making sense 🙌 #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #CodingTips
To view or add a comment, sign in
-
🔥 Stale Closure in React — A Common Bug You Must Know Ever faced a situation where your state is not updating correctly inside setTimeout / setInterval / useEffect? 🤯 👉 That’s called a Stale Closure --- 💡 What is happening? A function captures the old value of state and keeps using it even after updates. --- ❌ Example (Buggy Code): import { useState, useEffect } from "react"; function Counter() { const [count, setCount] = useState(0); useEffect(() => { setInterval(() => { console.log(count); // ❌ Always logs 0 (stale value) }, 1000); }, []); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); } 👉 Why? Because the closure captured "count = 0" when the effect first ran. --- ✅ Fix (Correct Approach): useEffect(() => { const id = setInterval(() => { setCount(prev => prev + 1); // ✅ always latest value }, 1000); return () => clearInterval(id); }, []); --- 🎯 Key Takeaway: Closures + async code (setTimeout, setInterval, event listeners) = ⚠️ potential stale state bugs --- 💬 Interview One-liner: “Stale closure happens when a function uses outdated state due to how closures capture variables.” --- 🚀 Mastering this concept = fewer bugs + stronger React fundamentals #ReactJS #JavaScript #Frontend #InterviewPrep #Closures #WebDevelopment
To view or add a comment, sign in
-
💡 Lesson Learned Today: While working on implementing search functionality in a React + Redux application, I faced an issue where the search input was updating correctly… but the results were not filtered at all 🤔 After debugging, I discovered an important insight: 👉 Not every “search issue” comes from the frontend. ✔️ The request was being sent correctly ✔️ The search parameter was included in the API call ❌ But the backend endpoint didn’t support filtering with that parameter 🔍 What I learned: Always verify: Is the correct parameter name being sent? Is the backend actually using it? Check the Network tab before assuming the issue 🚀 Sometimes the best debugging skill is knowing where the problem is NOT. #FrontendDevelopment #React #Redux #Debugging #WebDevelopment #LearningJourney
To view or add a comment, sign in
-
🚀 Most devs use Next.js every day but don't fully understand what happens under the hood. Let me break down Server vs Client Components in 60 seconds — and what the RSC Payload actually is. 🖥️ On the Server Next.js splits rendering by route segment (layouts + pages). → Server Components → rendered into an RSC Payload → Client Components + RSC Payload → prerendered HTML 📦 What is the RSC Payload? A compact binary representation of your Server Component tree. It contains 3 things: ✅ Rendered result of Server Components ✅ Placeholders + JS references for Client Components ✅ Props passed from Server → Client Components 💡 Why does this matter? React uses the RSC Payload on the client to update the DOM — not re-render everything from scratch. That's how Next.js gives you fast, seamless navigations while keeping server-rendered content fresh. Understanding this model helps you: → Write leaner bundles (keep logic server-side) → Pass props correctly across the boundary → Avoid hydration mismatches that are hard to debug #NextJS #React #WebDev #Frontend #JavaScript #ImmediateJoiner #CoreWebVitals
To view or add a comment, sign in
-
During one of my weekend online classes, I noticed all my classmates using the Go Live extension in VS Code. It worked fine — but sitting there, I kept thinking about all the things it couldn't do. What about React? What about Vue, Angular, or any SPA framework? What about having real browser DevTools without constantly Alt-Tabbing out of VS Code? What about running multiple projects at once? So I built my own. Meet Go Live Pro 🚀 Here's what makes it different: ✅ Works with ALL frameworks — React, Vue, Angular, Svelte — SPA fallback is built right in. No extra config. ✅ Embedded Chromium browser inside VS Code — See your live site without leaving the editor. Powered by a real Chromium instance, not just a webview iframe. ✅ Full DevTools inside the editor — Console, Elements Inspector, Storage viewer, Network+ tab. Everything you need, right where you code. ✅ Multi-root workspace support — Working on a monorepo? Run separate live servers for multiple folders simultaneously, each on their own port. ✅ Hot reload on every save — Instant WebSocket-based reload. HTML, CSS, JS — save and it's done. ✅ API Proxy — No more CORS headaches during local development. ✅ Responsive preview presets — Mobile, Tablet, Desktop — test them all with one click. I built this in TypeScript using the VS Code Extension API, Express, Chrome DevTools Protocol (CDP), chokidar for file watching, and WebSockets for live reload. The full architecture docs are in the repo if you want to dive deep. It's open source, MIT licensed, and open for contributions! 🙌 Whether it's a feature request, a bug fix, a framework-specific improvement, or documentation help — all PRs and issues are welcome. Let's build this together. 🔗 https://lnkd.in/gNVgR-9m Drop a ⭐ if you find it useful, and tag a dev friend who lives in VS Code! #VSCode #OpenSource #WebDevelopment #JavaScript #TypeScript #DevTools #BuildInPublic #100DaysOfCode #Frontend
To view or add a comment, sign in
More from this author
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