⚡ “The Event Loop Trap — Why Your Code Runs Out of Order” You write this 👇 console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Expected output? Start → Timeout → Promise → End Reality? Start → End → Promise → Timeout 👉 That’s the event loop catching you off guard. 🧠 Why This Happens JavaScript is single‑threaded but non‑blocking. The event loop orchestrates execution: Call Stack → Runs synchronous code first. Microtask Queue → Promises, await, queueMicrotask. Macrotask Queue → setTimeout, setInterval, DOM events. Loop → Sync → Microtasks → ONE Macrotask → Repeat 🔁 🚀 Angular Example In Angular 21–22 apps: You poll APIs every few seconds. You rely on signals + OnPush for reactivity. If you assume setTimeout(fn, 0) runs immediately, your UI may render stale data or lag behind user actions. Promise.resolve().then(() => console.log('Microtask')); setTimeout(() => console.log('Macrotask'), 0); Output: Microtask → Macrotask Angular’s signal‑first runtime depends on this ordering for predictable updates. ⚖️ Golden Rule (Never Forget) 1️⃣ Sync code first 2️⃣ Then all microtasks 3️⃣ Then one macrotask 🔁 Repeat 🔥 Why This Matters Debugging async issues Avoiding race conditions Predictable UI rendering Understanding why logs look “out of order” What output did you expect before reading this? 😅 #JavaScript #EventLoop #Angular #Signals #OnPush #Frontend #Performance #WebDevelopment #CleanCode #AsyncProgramming
The Event Loop Trap: Why Your Code Runs Out of Order
More Relevant Posts
-
Refactoring for Scalability: From individual states to clean, centralized objects. 🏗️ I’ve been spending my weekend deep-diving into React state management for my latest project, the Lumina Tech. The biggest "aha!" moment? Moving away from multiple useState hooks for every single input and refactoring my form logic into a single source of truth. By using a generic handleChange function with the Context API, I can now handle Name, Price, Category, and Quantity updates with just one clean function. It’s one thing to make a form work; it’s another to make it scalable. Current progress on the Lumina Tech: ✅ Centralized State: Managed via React Context for a cleaner component tree. ✅ Draft vs. Confirmed Logic: Separating "live typing" from the final "catalog upload." ✅ Professional UI: Leveraged react-icons and custom CSS for a modern inventory dashboard. Next up: Implementing the product grid and mastering nested routing! #ReactJS #WebDevelopment #FrontendEngineers #CodingJourney #JavaScript #BuildInPublic
To view or add a comment, sign in
-
-
Important Frontend Concepts Checklist- 1. Pagination 2. Infinite Scrollbar 3. Debouncing 4. Websocket 5. REST vs GraphQI APIs 6. Local Storage vs Cookies 7. Authentication vs Authorization 8. Redux ( Or any other state management library) 9. Lazy Loading 10. Code Splitting 11. Bundle Size Optimization 12. Tree Shaking 13. Memoization (useMemo, useCallback) 14. Caching (Client + Server) 15. CSR vs SSR vs SSG vs ISR 16. Core Web Vitals (LCP, INP, CLS) 17. Cross Browser Compatibility 18. Optimistic UI Updates 19. Suspense (React) 20. Image Optimization (WebP, AVIF) 21. Accessibility (a11y) 22. Webpack 23. Micro-Frontend Architecture 24. Unit Testing 25. Polyfills, Babel #ReactDeveloper #FrontEnd #FrontEndDeveloper #Javascript #Angular #AngularDeveloper #react #Typescript
To view or add a comment, sign in
-
Hook: We need to talk about the awkward phase between useState and installing Redux. For a long time, I defaulted to useState for literally everything. Then you hit a feature—like a complex multi-step form or a data-heavy dashboard—and suddenly your component has six different state setters. Your event handlers turn into a tangled mess of setLoading(false), setData(res), and setError(null), all firing at once and risking race conditions. That’s exactly when useReducer goes from being "that confusing React hook" to the most vital tool for clean architecture. ✅ When you SHOULD use it: Dependent State: When updating one piece of state requires changing another at the exact same time (e.g., resolving an API call updates loading, data, and error simultaneously). Complex Objects: When your state is a deeply nested object or array that requires precise mapping or filtering on every update. Centralizing Logic: When you want to pull messy update logic out of your UI component and into a pure, highly testable JavaScript function. You can unit-test a reducer without ever touching a React component. ❌ When you SHOULD NOT use it: Simple Primitives: Please don't write a 15-line reducer with action types and switch statements just to toggle a modal open and closed. useState is perfectly fine for isolated, flat values. Just to look "advanced": The boilerplate is real. If the state is simple, keep the code simple. Don't frustrate the next developer who reads your code just to flex a hook. 💡 Why it matters in production: At the product-company level, you don't always need Redux, Zustand, or MobX for every feature. Pairing useReducer with the Context API gives you a powerful, localized global state. You can pass the dispatch function down the tree, completely avoiding prop-drilling without bloating your bundle size with third-party dependencies. It takes a minute to shift your brain from "updating values" to "dispatching actions," but your future self (and your teammates) will thank you when debugging. What is your personal threshold for making the switch from useState to useReducer? Let's debate below. #ReactJS #FrontendEngineering #SoftwareArchitecture #CleanCode #JavaScript
To view or add a comment, sign in
-
-
Let’s talk about useEffect. Not just how to use it… but how to use it properly. Because this is where a lot of frontend issues start. First thing to understand: useEffect is for side effects. That means anything outside the normal render flow: – API calls – subscriptions – timers – interacting with the DOM It’s not a general-purpose tool for logic. Where most people get it wrong: They treat useEffect like: “run this code when the component loads” And then you start seeing things like: – multiple API calls – infinite loops – unnecessary re-renders – state updating in circles A simple example: If you do this: useEffect(() => { fetchData(); }); That runs on every render. Now imagine what happens when state updates… The correct approach is to be intentional: – run once → use [] – run on change → add specific dependencies But here’s the shift that changed things for me: I stopped asking “where can I use useEffect?” And started asking “do I even need useEffect here?” Because in many cases, you don’t. Instead: – derive values directly during render – use event handlers for interactions – use tools like React Query (TanStack Query) for data fetching React Query handles: – caching – background updates – loading & error states – request deduplication So you don’t have to manually manage all of that inside useEffect. That shift alone removes a lot of bugs. useEffect is not a “run code” tool. It’s a synchronisation tool. Once you understand that… your code becomes simpler and more predictable. #React #ReactQuery #Frontend #WebDevelopment #JavaScript #SoftwareEngineering
To view or add a comment, sign in
-
-
Dynamic forms let users add/remove fields on the fly — useful for things like multiple users, skills, or credentials. 🔹 Start with state Use useState to store an array of objects (each object = one form row). 🔹 Handle input changes Update specific fields using index + computed property names: Keeps state immutable and predictable. 🔹 Add fields Clone the array and insert a new empty object (unshift or push). 🔹 Remove fields Filter out the selected index, with a guard to keep at least one field. 🔹 Render dynamically Use .map() to generate inputs and bind each to its index. 💡 Key idea: Treat form fields as data, not UI. Once your state is structured well, the UI becomes easy. #React #Frontend #WebDevelopment #MERN #JavaScript
To view or add a comment, sign in
-
Higher-Order Components are often called “old React.” But that’s only half the story. In React, HOCs introduced one of the most important ideas in frontend architecture: 👉 Separating behavior from UI Most developers focus on what components render But scalable systems depend on how behavior is reused That’s where HOCs changed the game: Wrap components without modifying them Inject logic like auth, logging, loading Keep UI clean and focused ⚡ Where HOCs still matter today: • Legacy codebases • Authentication & route guards • Analytics / logging layers • Enterprise abstraction layers 🧠 What I learned working on real systems: Hooks made things simpler — no doubt. But they didn’t replace the idea behind HOCs. Because at scale: 👉 You don’t just write components 👉 You design reusable behavior layers 💡 The real takeaway: HOCs are not about syntax. They’re about thinking in abstractions. And once you start thinking this way — your frontend code becomes: ✔️ Cleaner ✔️ More reusable ✔️ Easier to scale #️⃣ #reactjs #frontenddevelopment #javascript #softwarearchitecture #webdevelopment #coding #reactpatterns
To view or add a comment, sign in
-
-
Most React devs are one bad library choice away from a refactor they didn't plan for. Here are the 9 that actually belong in your 2026 stack 👇 Zustand v5 — State Management Hook-based, zero boilerplate, persist and devtools built in. Rated #1 DX in State of React 2025. TanStack Query - Server State Kills 80% of your useEffect fetching code. Caching, refetch, optimistic updates - all declarative. shadcn/ui - Components Not a library. You copy it into your repo. You own it. No lock-in, full Tailwind control. React Hook Form + Zod — Forms Near-zero re-renders. TypeScript validation end to end. Nothing else comes close on performance. Motion — Animation Declarative, gesture-aware, scroll-driven. Formerly Framer Motion. Still the top pick. MUI v6 — Enterprise UI 4.5M downloads per week. 97K stars. The baseline for large teams that need to move fast. TanStack Router — Routing Full TypeScript inference from URL to component props. Catches bugs React Router never will. Radix Primitives — Headless A11y WAI-ARIA compliant, zero styles, full control. The foundation under shadcn/ui. TanStack Table — Data Grids 100K+ row virtualization. Pure logic, zero UI opinion. Ask what to use for tables. Answer is always this. The pro stack: Zustand + TanStack Query + shadcn/ui + RHF/Zod + Motion + TanStack Router Save this. Use it on your next project. What's already in your stack? 👇 #ReactJS #JavaScript #Frontend #WebDev #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 𝗔𝗻𝗴𝘂𝗹𝗮𝗿 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀: 𝗧𝗵𝗲 𝗙𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹 𝗨𝗜 𝗕𝘂𝗶𝗹𝗱𝗶𝗻𝗴 𝗕𝗹𝗼𝗰𝗸𝘀! 🏗️💎 In the Angular world, a 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁 is more than just a piece of UI—it is a self-contained unit of logic, data, and presentation. It is essentially a Specialized Directive with its own template. In Angular v18+, the component model has reached a new level of efficiency with 𝗦𝗶𝗴𝗻𝗮𝗹𝘀 and 𝗦𝘁𝗮𝗻𝗱𝗮𝗹𝗼𝗻𝗲 architecture. 💡 𝗧𝗵𝗲 𝗗𝗲𝗲𝗽 𝗔𝗿𝗰𝗵𝗶𝘁𝗲𝗰𝘁𝘂𝗿𝗮𝗹 𝗕𝗿𝗲𝗮𝗸𝗱𝗼𝘄𝗻: 𝟭. 𝗧𝗵𝗲 𝗧𝗵𝗿𝗲𝗲-𝗣𝗶𝗹𝗹𝗮𝗿 𝗠𝗲𝘁𝗮𝗱𝗮𝘁𝗮 (@𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁) 🧬 Every component is defined by its metadata: 𝗧𝗲𝗺𝗽𝗹𝗮𝘁𝗲: The HTML that defines the view. 𝗦𝘁𝘆𝗹𝗲𝘀: Encapsulated CSS that ensures styles don't "leak" to other parts of the app. 𝗖𝗹𝗮𝘀𝘀: The TypeScript logic that manages the state and handles user interaction. This encapsulation makes components highly reusable and easy to test. 𝟮. 𝗦𝗶𝗴𝗻𝗮𝗹-𝗕𝗮𝘀𝗲𝗱 𝗦𝘁𝗮𝘁𝗲 𝗠𝗮𝗻𝗮𝗴𝗲𝗺𝗲𝗻𝘁 🎯 With v18, components are moving away from traditional ChangeDetectionStrategy. Default. By using 𝗦𝗶𝗴𝗻𝗮𝗹𝘀, components can now track state changes with "Fine-Grained" precision. This means when a variable changes, Angular knows exactly which part of the DOM to update, enabling a 𝗭𝗼𝗻𝗲𝗹𝗲𝘀𝘀 future with unmatched performance. 𝟯. 𝗟𝗶𝗳𝗲𝗰𝘆𝗰𝗹𝗲 & 𝗥𝗲𝗮𝗰𝘁𝗶𝘃𝗲 𝗛𝗼𝗼𝗸𝘀 🔄 From ngOnInit to the modern afterRender and afterNextRender hooks, components give you full control over the execution flow. Whether you are fetching data from a service or manipulating the DOM after a render, the component lifecycle ensures your logic runs at the perfect moment, maintaining a smooth and predictable user experience. #Angular #WebDevelopment #ComponentArchitecture #FrontendEngineering #AngularSignals #CleanCode #SoftwareArchitecture #Typescript #Javascript #CodingTips #TechDeepDive #Angular18 #JeevrajSinghRajput #FrontendArchitecture #TechCommunity #ModernWeb #UIUXDesign #ReactiveProgramming #UIPerformance #AngularDev #WebDev #SoftwareEngineering #Architecture
To view or add a comment, sign in
-
-
Every useEffect that sets up a subscription, timer, or event listener must clean up after itself. ```js // Memory leak — listener accumulates on every render useEffect(() => { window.addEventListener('resize', handleResize); // No cleanup — listener is never removed }); // Correct — cleanup runs before next effect and on unmount useEffect(() => { window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); ``` Other effects that require cleanup: ```js // Timers const timer = setTimeout(callback, 1000); return () => clearTimeout(timer); // Fetch abort const controller = new AbortController(); fetch(url, { signal: controller.signal }); return () => controller.abort(); // Subscriptions const sub = observable.subscribe(handler); return () => sub.unsubscribe(); ``` Memory leaks accumulate silently. Clean up your effects — every time. #ReactJS #JavaScript #Frontend #WebDevelopment
To view or add a comment, sign in
-
Why does your 'ref' return 'null' the moment you wrap your input in a custom component? It is one of those React quirks that trips up even experienced developers. By default, refs do not behave like props. They are treated as special instances that stop at the component boundary to protect encapsulation. This is exactly why we need 'forwardRef'. It acts as a bridge that allows a parent component to reach through a child and grab a direct handle on an internal DOM node. The most practical application is building a reusable UI library. If you create a custom 'Input' or 'Button' component, your parent component might need to call '.focus()' or '.scrollIntoView()'. Without 'forwardRef', your parent is just holding a reference to a React internal object, not the actual HTML element. Another real-world scenario involves Higher-Order Components (HOCs). If you wrap a component with a 'withAnalytics' or 'withTheme' wrapper, that wrapper will 'swallow' the ref by default. By using 'forwardRef' in your HOC implementation, you ensure the reference passes through the wrapper and lands on the component that actually needs it. It is about making your abstractions transparent and ensuring that the parent component maintains the control it expects over the physical DOM. Using this pattern sparingly is key. It is an escape hatch for those moments where declarative state isn't enough to manage physical browser behavior. It keeps your component interfaces clean while providing the necessary access for specialized UI interactions. #ReactJS #SoftwareEngineering #Frontend #WebDevelopment #Javascript #CodingTips #CodingBestPractices
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
This is were most of the developers make mistake