🤔 Ever been confused why Promise.then() runs before setTimeout(..., 0)… even though the timeout is “0ms”? That’s microtasks vs macrotasks. 🧠 JavaScript interview question What’s the difference between a microtask and a macrotask, and how does the event loop order them? ✅ Short answer Macrotasks = the “main queue” jobs (timers, events, I/O callbacks) Microtasks = “right-after-this” jobs (Promises, queueMicrotask) After a macrotask finishes, the engine drains ALL microtasks before moving on (and before painting) 🔍 A bit more detail Think of each event loop turn like this: Run one macrotask (e.g. click handler, setTimeout callback) Run all pending microtasks (and if microtasks schedule more microtasks, keep going) Browser can render/paint Next macrotask So microtasks have higher priority than timers. 💻 Example (the classic “wait… why?!”) console.log("start"); setTimeout(() => console.log("timer"), 0); Promise.resolve().then(() => console.log("promise")); console.log("end"); Output: start end promise timer Because: setTimeout schedules a macrotask then() schedules a microtask microtasks run before the next macrotask ⚠️ Small but important Microtasks are powerful… but dangerous if abused. If you keep queuing microtasks in a loop, you can starve rendering and make the UI feel frozen. ⚛️ React tie-in This is why you’ll sometimes see UI not update “immediately” when you chain a lot of Promise work. The browser can’t paint until the microtask queue is done, so heavy microtask chains can make rendering feel delayed. #javascript #webdev #frontend #reactjs #nodejs #eventloop #async #promises #performance #softwareengineering
Microtasks vs Macrotasks: Understanding Event Loop Order
More Relevant Posts
-
𝐘𝐨𝐮'𝐫𝐞 𝐩𝐫𝐨𝐛𝐚𝐛𝐥𝐲 𝐦𝐢𝐬𝐮𝐬𝐢𝐧𝐠 `useState` 𝐟𝐨𝐫 𝐬𝐨𝐦𝐞𝐭𝐡𝐢𝐧𝐠 `useRef` 𝐝𝐨𝐞𝐬 𝐛𝐞𝐭𝐭𝐞𝐫. I've seen so many devs (and honestly, I've been there too!) grab `useState` for holding onto values that don't need to trigger a re-render. Think about it: a reference to a DOM element, a timer ID, or any mutable value you want to persist across renders without re-rendering the component. That's where `useRef` truly shines. Unlike `useState`, `useRef` gives you a mutable `current` property that persists across the component's lifecycle. Updating `ref.current` doesn't cause a re-render. This is crucial for: * **Direct DOM manipulation:** Accessing an `<input>` to `focus()` it. * **Storing mutable values:** A `setInterval` ID you need to `clearInterval`. * **Preventing unnecessary re-renders:** Keeping track of an internal flag without triggering the component to re-render. If your component doesn't need to react to a value change, it probably belongs in a `useRef`. Over-using `useState` here can lead to subtle performance issues and make your components harder to reason about. ```javascript // Don't do this (if you don't need re-render): // const [inputValueRef, setInputValueRef] = useState(null); // Do this: const inputRef = useRef(null); const handleButtonClick = () => { if (inputRef.current) { inputRef.current.focus(); } }; // <input ref={inputRef} /> ``` It's a small distinction, but it can make a big difference in how clean and performant your React components are. What's one common `useState` vs `useRef` pitfall you've encountered or solved? #React #ReactHooks #FrontendDev #JavaScript #WebDevelopment
To view or add a comment, sign in
-
𝗘𝘃𝗲𝗿 𝗵𝗲𝗮𝗿𝗱 𝗼𝗳 "𝗧𝗲𝗮𝗿𝗶𝗻𝗴" 𝗶𝗻 𝗥𝗲𝗮𝗰𝘁? With React 18's Concurrent Rendering, a new class of UI bugs emerged. "Tearing" is a visual glitch where your screen shows inconsistent data at the exact same time. 𝗧𝗵𝗲 𝗦𝗰𝗲𝗻𝗮𝗿𝗶𝗼: 1. Imagine a global theme variable living outside of React state: 2. React renders your <Header /> (Reads: Light Mode) 3. React pauses rendering to handle a high-priority user click. 4. That click changes the external theme in the background! 5. React resumes and renders <Footer /> (Reads: Dark Mode) The Result: A "torn" UI with a Light header and Dark footer. check out the snippet to understand how you fix it using 𝘂𝘀𝗲𝗦𝘆𝗻𝗰𝗘𝘅𝘁𝗲𝗿𝗻𝗮𝗹𝗦𝘁𝗼𝗿𝗲 Have you faced a challenge like this? let me know in comments #ReactJS #WebDevelopment #Frontend #JavaScript #React18
To view or add a comment, sign in
-
-
What I Learned Today: React State Management ✔️ What is State in React ✔️ How useState works ✔️ How state updates trigger re-renders ✔️ Managing dynamic UI with state Understanding state changed how I think about building components. Next: Exploring props vs state deeply. #React #JavaScript #Frontend #BuildInPublic
To view or add a comment, sign in
-
💡 SolidJS Tip: Use <Switch> and <Match> for Clean Conditional UI When your UI depends on multiple conditions, instead of writing messy if / else logic, SolidJS gives you a cleaner solution. ✅ Solid checks each <Match> from top to bottom ✅ The first true condition renders ✅ If nothing matches → fallback appears ⚡ Quick rule • <Show> → one condition • <Switch> → multiple conditions Clean code = easier maintenance. #SolidJS #JavaScript #Frontend #WebDevelopment #CodingTips
To view or add a comment, sign in
-
-
𝐈𝐬 𝐲𝐨𝐮𝐫 𝐑𝐞𝐚𝐜𝐭 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭 𝐫𝐞-𝐫𝐞𝐧𝐝𝐞𝐫𝐢𝐧𝐠 𝐮𝐧𝐧𝐞𝐜𝐞𝐬𝐬𝐚𝐫𝐢𝐥𝐲 𝐛𝐞𝐜𝐚𝐮𝐬𝐞 𝐲𝐨𝐮'𝐫𝐞 𝐭𝐫𝐚𝐜𝐤𝐢𝐧𝐠 𝐚 𝐯𝐚𝐥𝐮𝐞 𝐭𝐡𝐚𝐭 𝐝𝐨𝐞𝐬𝐧'𝐭 𝐧𝐞𝐞𝐝 𝐭𝐨 𝐮𝐩𝐝𝐚𝐭𝐞 𝐭𝐡𝐞 𝐔𝐈? We often reach for `useState` by default for any mutable value that needs to persist across renders. But here's the catch: changes to `useState` values trigger a re-render. If you're tracking something like a timer ID, an external library instance, or even just the previous value of a prop purely for internal logic, triggering a re-render for those changes is often wasteful. Enter `useRef`. It's perfect for holding mutable values that should persist across renders but whose changes do not need to cause your component to re-render. Its `.current` property can be updated directly, and React won't bat an eye (or re-render your component). Think of `useRef` as a consistent box you can put things in, access later, and change without telling React to redraw the whole screen. ```jsx // Bad (often) for non-UI-critical values: const [myTimerId, setMyTimerId] = useState(null); // Triggers re-render on ID change // Better for internal mutable values that don't need UI updates: const myTimerIdRef = useRef(null); // Assign later: myTimerIdRef.current = setTimeout(...) // Access later: clearInterval(myTimerIdRef.current) ``` This tiny shift can make a noticeable difference in performance-sensitive components, especially when dealing with frequent internal updates. When do you find yourself reaching for `useRef` over `useState`? Share your patterns! #React #FrontendDevelopment #JavaScript #WebDev #Performance
To view or add a comment, sign in
-
REACT INTERNALS - PART 1 What Does “Rendering” Actually Mean? In React, we often say: “This component re-rendered.” But rendering does NOT mean the browser immediately updated the screen. When you click a button that updates state, here’s what actually happens: 1. setState (or setCount) updates the state value 2. React schedules an update 3. The component function runs again 4. React calculates what the UI should look like now This calculation phase is called rendering. At this stage, React creates a new Virtual DOM - a lightweight JavaScript representation of the UI. The browser, however, works with the Actual DOM - the real structure displayed on the screen. Updating the Actual DOM is expensive because it can trigger layout recalculation, repaint, and reflow inside the browser. To avoid unnecessary work, React compares the new Virtual DOM with the previous one. Only after finding differences does it update the Actual DOM. So the key idea is: Rendering = recalculating the UI DOM update = applying real changes in the browser They are not the same thing. Understanding this separation is the first step toward understanding performance in React. To understand this better, refer to the example attached below. Next: How React compares the old and new Virtual DOM - reconciliation. #ReactJS #FrontendDevelopment #JavaScript #ReactInternals #SoftwareEngineering
To view or add a comment, sign in
-
-
React.memo does NOT stop re-renders. Even if props don’t change. State update? → Re-render. Context update? → Re-render. React.memo only compares props. That’s it. It’s not a render lock. It’s not magic. It’s a shallow comparison. If your memoized component still re-renders… That’s expected. Stop assuming. Start understanding. Did you know this before today? #react #javascript #frontend #webdev #performance
To view or add a comment, sign in
-
-
While developing a new feature, I ran into a specific need: map a path to a different location — without changing the URL in the browser. That's exactly what Next.js rewrites do. Instead of duplicating layouts or restructuring the whole feature, I just added a rewrites config directly in next.config.js The URL stays exactly what it needs to be. The layout stays in one place. Problem solved. #Nextjs #WebDevelopment #JavaScript #Frontend #React
To view or add a comment, sign in
-
-
𝗠𝗼𝘀𝘁 𝗥𝗲𝗮𝗰𝘁 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝘂𝘀𝗲 𝘁𝗵𝗲 𝘄𝗿𝗼𝗻𝗴 𝗵𝗼𝗼𝗸 𝗮𝗻𝗱 𝗱𝗼𝗻’𝘁 𝗲𝘃𝗲𝗻 𝗿𝗲𝗮𝗹𝗶𝘇𝗲 𝗶𝘁. useEffect vs useLayoutEffect in React 19.2 You think they’re the same? They’re not. The difference is timing. 👉 𝘂𝘀𝗲𝗘𝗳𝗳𝗲𝗰𝘁 • Runs after the browser paints • Does NOT block the UI • Best for API calls, subscriptions, timers, logging • Default choice in most cases 👉 𝘂𝘀𝗲𝗟𝗮𝘆𝗼𝘂𝘁𝗘𝗳𝗳𝗲𝗰𝘁 • Runs before the browser paints • Blocks the UI until it finishes • Best for measuring DOM, fixing scroll position, layout adjustments 𝗤𝘂𝗶𝗰𝗸 𝗥𝘂𝗹𝗲: If it affects layout or you need to measure something before the screen updates → useLayoutEffect Everything else → useEffect Small difference. Big impact on UI performance. #ReactJS #Frontend #WebDevelopment #JavaScript #fullstackdev #dashdev
To view or add a comment, sign in
-
-
State vs Refs in React is one of the simplest concepts… and one of the most common sources of bugs. Here’s the mental model I use: ✅ State (useState) = renders UI If changing it should update what the user sees → it belongs in state. ✅ Ref (useRef) = remembers without re-rendering Perfect for DOM nodes, timers, previous values, websocket instances, and “latest value” patterns to avoid stale closures. Quick rule: State renders. Ref remembers. #React #ReactJS #JavaScript #TypeScript #FrontendDevelopment #WebDevelopment #ReactHooks #useState #useRef #Performance #UIUX #SoftwareEngineering #CleanCode #DeveloperTips #FrontendArchitecture
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