🔥 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
Stale Closure in React: A Common Bug
More Relevant Posts
-
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
-
-
If you’ve written even a single line of React, you’ve done this: '<button onClick={() => handleClick(id)}>'. But have you ever paused to ask why we wrap it in an anonymous arrow function instead of just passing the handler directly? It’s not just a syntax preference; it’s about controlling when your code actually runs. The most common trap for beginners is writing `onClick={handleClick()}`. In JavaScript, adding those parentheses means "execute this right now." If you do that in React, your function runs the moment the component renders, often leading to the dreaded "Too many re-renders" error if your handler updates state. By wrapping it in an arrow function, you’re passing a reference to a function that says: "Don't run this yet. Wait until the user actually clicks." Another major reason is argument passing. If your handler needs a specific ID or an index from a loop, the arrow function acts as a closure. It "captures" that specific value from the current render cycle and carries it into the function call later. Back in the day of Class Components, we used arrow functions (or '.bind(this)') to solve the 'this' context nightmare, but in the era of Hooks, the focus has shifted entirely to execution control and data scoping. Is there a downside? Technically, yes. Every time your component re-renders, a new function instance is created. In 99% of applications, this is a micro-optimization that doesn't matter. But if you're passing that function down to a heavily optimized 'React.memo' child, that new reference might trigger unnecessary renders. That’s where 'useCallback' enters the chat. #ReactJS #WebDevelopment #SoftwareEngineering #Javascript #CodingBestPractices
To view or add a comment, sign in
-
𝐈𝐬 𝐲𝐨𝐮𝐫 `𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭` 𝐫𝐮𝐧𝐧𝐢𝐧𝐠 𝐰𝐡𝐞𝐧 𝐢𝐭 𝐬𝐡𝐨𝐮𝐥𝐝𝐧'𝐭? 𝐓𝐡𝐞 𝐜𝐮𝐥𝐩𝐫𝐢𝐭 𝐦𝐢𝐠𝐡𝐭 𝐛𝐞 𝐦𝐨𝐫𝐞 𝐬𝐮𝐛𝐭𝐥𝐞 𝐭𝐡𝐚𝐧 𝐲𝐨𝐮 𝐭𝐡𝐢𝐧𝐤. I just spent a frustrating hour debugging a seemingly random data refetch in a React component, only to trace it back to a non-primitive dependency in my `useEffect` array. When you pass an object or a function created inside your component directly into `useEffect`'s dependency array, React performs a reference equality check. Even if the contents of your object or the logic of your function haven't changed, its reference is new on every render. This forces your effect to re-run unnecessarily. Here's the common trap: ```javascript // 🚨 Problematic: 'config' object reference changes on every render const MyComponent = ({ id }) => { const config = { userId: id, status: 'active' }; useEffect(() => { fetchData(config); }, [config]); // 💥 Effect re-runs even if 'id' hasn't changed // ... }; ``` A cleaner, more performant way is to stabilize those references. For configuration objects, `useMemo` is your friend: ```javascript // ✅ Solution: 'memoizedConfig' reference is stable as long as 'id' is const MyComponent = ({ id }) => { const memoizedConfig = useMemo(() => ({ userId: id, status: 'active' }), [id]); useEffect(() => { fetchData(memoizedConfig); }, [memoizedConfig]); // ... }; ``` This prevents wasted renders and unnecessary side effects, keeping your app snappier and less buggy. It's often the small details in `useEffect` that lead to the biggest headaches! Have you ever battled a similar `useEffect` dependency bug? What was your fix? #ReactJS #FrontendDevelopment #JavaScript #WebDev #ReactHooks
To view or add a comment, sign in
-
React recap: 𝗨𝘀𝗶𝗻𝗴 𝗶𝗻𝗱𝗲𝘅 𝗮𝘀 𝗮 𝘂𝗻𝗶𝗾𝘂𝗲 𝗜𝗗 𝘄𝗮𝘀 𝗺𝘆 𝗯𝗶𝗴𝗴𝗲𝘀𝘁 𝗺𝗶𝘀𝘁𝗮𝗸𝗲 𝗶𝗻 𝗥𝗲𝗮𝗰𝘁. At first, it felt harmless. items.map((item, index) => ( <Component key={index} /> )) Everything worked… until it didn’t. Here’s what I learned the hard way: • When the list changes (add/remove/reorder), React gets confused • Components don’t re-render correctly • State sticks to the wrong items (this one is scary) • Bugs appear that make zero sense at first I spent hours debugging something that wasn’t even obvious. The real problem? Index is not a stable identity. So what should we do instead? ✔️ Use a unique ID from your data (database ID, UUID, etc.) ✔️ Generate stable IDs (not on every render) ✔️ Think of keys as identity, not position Bad: key={index} Good: key={item.id} Simple change. Massive difference. One small mistake can quietly break your entire UI logic. If you're using index as key — fix it before it fixes you. #React #Frontend #WebDevelopment #JavaScript #CodingLessons
To view or add a comment, sign in
-
-
1,200 lines of form code deleted from a production dashboard — and the forms actually work better now. That's what happens when you swap React Hook Form for React 19's built-in Actions + useActionState on the right kind of project. Here's the thing most tutorials won't tell you: this isn't a blanket "RHF is dead" story. It's a "know when to use what" story. → Simple CRUD forms (login, contact, settings)? useActionState + useOptimistic handles it natively. No extra deps, no bundle cost, instant optimistic UI out of the box. → Complex dynamic forms (nested arrays, conditional fields, 50+ field wizards)? React Hook Form still wins. React 19 has no built-in validation beyond HTML attributes — and managing deeply nested field arrays without RHF is pain you don't need. → The middle ground is where it gets interesting. Forms with 5–15 fields and basic Zod validation? You can go either way. We leaned native and didn't look back. The real unlock isn't "drop the library." It's that React's form primitives finally work well enough that you can evaluate each form on its own complexity instead of reaching for RHF by default on every project. Three questions before you refactor: 1. Do any of your forms have dynamic field arrays? 2. Are you using RHF's validation resolver pattern heavily? 3. Is your form state shared across multiple components? If you answered "no" to all three, you might be carrying a dependency you don't need. What's your team's take still all-in on React Hook Form, or have you started migrating simpler forms to Actions? #ReactJS #FrontendDevelopment #WebDev #JavaScript #React19 #FormHandling #DeveloperProductivity
To view or add a comment, sign in
-
🚀 Debugging JWT Auth — A Small Mistake That Cost Me Hours Today I ran into a classic authentication issue while working with NestJS + Next.js — and it’s a good reminder of how small misunderstandings can break the whole flow. 🔍 The Problem After login, I noticed that my localStorage was saving: token: "string" Instead of an actual JWT like: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ⚠️ Clearly something was off. 🧠 The Root Cause My backend response looked like this: { "success": true, "data": { ...userDetails }, "token": "REAL_JWT_TOKEN" } But in my frontend, I made this mistake: const userData = res.data.data; localStorage.setItem("token", userData.token); // ❌ wrong 👉 The token wasn’t inside data — it was at the root level. ✅ The Fix const userData = res.data.data; const token = res.data.token; localStorage.setItem("token", token); localStorage.setItem("userData", JSON.stringify(userData)); 🔥 Debug smarter, not harder. #WebDevelopment #NestJS #NextJS #JWT #Authentication #Debugging #FullStack #JavaScript
To view or add a comment, sign in
-
JavaScript Closures are confusing… until they’re not ⚡ Most developers memorize the definition but struggle to actually understand it. Let’s simplify it 👇 💡 What is a closure? A closure is when a function 👉 remembers variables from its outer scope even after that scope is finished 🧠 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const fn = outer(); fn(); // 1 fn(); // 2 fn(); // 3 ⚡ Why this works: inner() still has access to count even after outer() has executed 🔥 Where closures are used: • Data hiding • State management • Event handlers • Custom hooks in React #JavaScript #FrontendDeveloper #ReactJS #CodingTips #WebDevelopment
To view or add a comment, sign in
-
Stop guessing the order of your console.logs. 🛑 JavaScript is single-threaded. It has one brain and two hands. So, how does it handle a heavy API call, a 5-second timer, and a button click all at once without catching fire? It’s all about the Event Loop, but specifically, the "VIP treatment" happening behind the scenes. The Two Queues You Need to Know: 1. The Microtask Queue (The VIP Line) 💎 What lives here: Promises (.then), await, and MutationObserver. The Rule: The Event Loop is obsessed with this line. It will not move on to anything else until this queue is bone-dry. If a Promise creates another Promise, JS stays here until they are all done. 2. The Macrotask Queue (The Regular Line) 🎟️ What lives here: setTimeout, setInterval, and I/O tasks. The Rule: These tasks are patient. The Event Loop only picks one at a time, then goes back to check if any new VIPs (Microtasks) have arrived. The "Aha!" Moment Interview Question: What is the output of this code? (Most junior devs get this wrong). JavaScript console.log('Start'); setTimeout(() => console.log('Timeout'), 0); Promise.resolve().then(() => console.log('Promise')); console.log('End'); The Reality: 1. Start (Sync) 2. End (Sync) 3. Promise (Microtask - Jumps the line!) 4. Timeout (Macrotask - Even at 0ms, it waits for the VIPs) The Pro-Tip for Performance 💡 If you have a heavy calculation, don't wrap it in a Promise thinking it makes it "background." It’s still on the main thread! Use Web Workers if you really want to offload the heavy lifting. Does the Event Loop still confuse you, or did this click? Let's discuss in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
-
🚀 Why useState is a Game-Changer in React. let's breakdown this 👇 💡 What is useState? "useState" is a React Hook that allows you to store and manage dynamic data (state) inside functional components. Without it, your UI wouldn’t respond to user input. 📱 Real-Time Example: Form Input & Validation Let’s take a simple login form 👇 import React, { useState } from "react"; function LoginForm() { const [email, setEmail] = useState(""); const [error, setError] = useState(""); const handleSubmit = (e) => { e.preventDefault(); if (!email.includes("@")) { setError("Please enter a valid email address"); } else { setError(""); alert("Form submitted successfully!"); } }; return ( <form onSubmit={handleSubmit}> <input type="text" placeholder="Enter email" value={email} onChange={(e) => setEmail(e.target.value)} /> {error && <p style={{ color: "red" }}>{error}</p>} <button type="submit">Submit</button> </form> ); } export default LoginForm 🧠 What’s happening here? - "email" → stores user input - "setEmail" → updates input as the user types - "error" → stores validation message - "setError" → shows/hides error instantly useState is what connects user actions to UI behavior. It ensures your forms are not just functional, but smart and responsible 💬 Have you implemented form validation using useState? What challenges did you face? #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #Coding
To view or add a comment, sign in
-
A lot of people constantly ask me what React Hooks actually are, and the best way to think about Hooks and JavaScript concepts in general is to look at what problem they were trying to fix. For example, before React Hooks, people would create a Container Component and a Presentational Component. The Container Component would retrieve data, like making a fetch request, and then pass that data down to the Presentational Component, which was usually a pure function that returned some UI, like a div with styling, and accepted that data as props. This pattern helped create a standard for how data was retrieved in React and enforced separation of concerns, but it ended up being too boilerplate heavy for most people. So Hooks were introduced to let us hook into components directly, allowing us to load data as a side effect inside a function while still maintaining separation of concerns without needing extra components. #ReactJs #JavaScript #JavaScriptHooks
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