𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐂𝐥𝐨𝐬𝐮𝐫𝐞 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 Many developers understand closures in JavaScript… but get confused when it comes to React. Question: What will be the output of this code? Example 👇 import React, { useState } from "react"; export default function App() { const [count, setCount] = useState(0); const handleClick = () => { setTimeout(() => { console.log(count); }, 1000); }; return ( <> Click </> ); } Now imagine: You click the button 3 times quickly and count updates each time What will be logged after 1 second? Answer 👇 It will log the SAME value multiple times ❌ Why? Because of closure. The setTimeout callback captures the value of count at the time handleClick was created. This is called a “stale closure”. Correct approach ✅ setTimeout(() => { setCount(prev => { console.log(prev); return prev; }); }, 1000); Or use useRef for latest value. Tip for Interview ⚠️ Closures + async code can lead to stale state bugs in React. Good developers know closures. Great developers know how closures behave in React. #ReactJS #JavaScript #Closures #FrontendDeveloper #WebDevelopment #ReactInterview #CodingInterview #ReactHooks
React Closures: Understanding Stale State Bugs
More Relevant Posts
-
𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐂𝐥𝐨𝐬𝐮𝐫𝐞 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 Many developers understand closures in JavaScript… but get confused when it comes to React. Question: What will be the output of this code? Example 👇 import React, { useState } from "react"; export default function App() { const [count, setCount] = useState(0); const handleClick = () => { setTimeout(() => { console.log(count); }, 1000); }; return ( <> <button onClick={handleClick}> Click </button> <button onClick={() => setCount(count + 1)}> Increase Count ({count}) </button> </> ); } Now imagine: You click the button 3 times quickly and count updates each time What will be logged after 1 second? Answer 👇 It will log the SAME value multiple times ❌ Why? Because of closure. The setTimeout callback captures the value of count at the time handleClick was created. This is called a “stale closure”. Correct approach ✅ useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, [count]); Or use useRef for latest value. Tip for Interview ⚠️ Closures + async code can lead to stale state bugs in React. Good developers know closures. Great developers know how closures behave in React. #ReactJS #JavaScript #Closures #FrontendDeveloper #WebDevelopment #ReactInterview #CodingInterview #ReactHooks
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
-
Most React Native codebases become a mess by month 3. Not because the developer was bad. Because nobody agreed on a structure from day one. Here's the folder structure I use on every project 👇 src/ ├── components/ → reusable UI only ├── screens/ → one file per screen ├── navigation/ → all route config here ├── hooks/ → useAuth, usePlayer, useBooking ├── store/ → Redux slices ├── services/ → ALL API calls live here ├── utils/ → helpers & constants ├── types/ → TypeScript interfaces └── assets/ → images & fonts 3 rules I never break: 🔴 API calls never go inside components 🟡 Every colour lives in theme.ts — nowhere else 🟢 Types folder grows with the project — never skip it Junior me put everything in /components. 6 months later it had 60 files and zero logic separation. Never again. Save this before your next project 👇 #ReactNative #TypeScript #CleanCode #MobileDev #JavaScript #2026
To view or add a comment, sign in
-
-
🚀 Closure in JavaScript — Explained Like a Senior React Developer Closures are one of those concepts that look simple… but power some of the most critical patterns in React ⚡ 👉 What is a Closure? A closure is when a function remembers variables from its outer scope, even after the outer function has finished execution. 💡 In short: Function + Lexical Scope = Closure --- 🔹 Basic Example function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 👉 Even though outer() is done, inner() still remembers count That’s the power of closure. --- 🔹 Why Closures Matter in React? Closures are everywhere in React: ✔️ Hooks (useState, useEffect) ✔️ Event handlers ✔️ Async operations (setTimeout, API calls) ✔️ Custom hooks --- 🔹 Real-world React Problem: Stale Closure ⚠️ setCount(count + 1); setCount(count + 1); ❌ Both use the same old value of count ✅ Correct approach: setCount(prev => prev + 1); setCount(prev => prev + 1); 👉 This avoids stale closure and ensures latest state is used --- 🔹 Where Closures Help ✅ Data encapsulation (private variables) ✅ Memoization & performance optimization ✅ Debouncing / throttling ✅ Custom hooks ✅ Cleaner state management --- 🔥 Pro Insight (Senior Level) Closures are the backbone of React’s functional paradigm. Misunderstanding them can lead to bugs in: useEffect dependencies Async logic Event callbacks --- 💬 One-line takeaway 👉 “Closures allow functions to retain access to their scope — making React hooks and async logic work seamlessly.” --- #JavaScript #ReactJS #Frontend #WebDevelopment #Programming #InterviewPrep #SoftwareEngineering
To view or add a comment, sign in
-
JSX is where logic meets design, turning simple { } into powerful, dynamic interfaces that breathe life into your React apps. Learn how expressions shape real UI and avoid common pitfalls along the way. 👉 Master it here: https://lnkd.in/dMfnqU-i #ReactJS #JSX #WebDevelopment #FrontendDevelopment #JavaScript #CodingLife #LearnToCode #DeveloperJourney #TechSkills
To view or add a comment, sign in
-
𝐀𝐝𝐯𝐚𝐧𝐜𝐞𝐝 𝐑𝐞𝐚𝐜𝐭 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🚀 Many developers use "key" in React… but don’t fully understand why it’s important. Question: Why should we NOT use index as key in React lists? 🤔 Example 👇 const items = ["A", "B", "C"]; items.map((item, index) => ( Looks fine… right? ❌ Now imagine removing "A" from the list 👇 ["B", "C"] React will reuse DOM elements incorrectly because index changes. Result? ⚠️ Wrong UI updates ⚠️ State mismatch ⚠️ Unexpected bugs Correct way ✅ items.map((item) => ( Why? React uses "key" to track elements during reconciliation (Virtual DOM diffing). If keys are unstable (like index), React cannot correctly identify elements. Tip for Interview ⚠️ Key should be: ✔ Unique ✔ Stable ✔ Predictable Good developers write lists. Great developers understand reconciliation. #ReactJS #FrontendDeveloper #JavaScript #WebDevelopment #ReactInterview #AdvancedReact #CodingInterview #SoftwareDeveloper
To view or add a comment, sign in
-
-
🤔 useMemo and useCallback confuse almost every React developer. Here’s the clearest way to think about it 👇 🧠 Core idea: → useMemo = cache a VALUE → useCallback = cache a FUNCTION REFERENCE 💻 Example: // useMemo — don't recalculate unless deps change const total = useMemo(() => cart.reduce((sum, item) => sum + item.price, 0), [cart] ); // useCallback — don't recreate unless deps change const handleClick = useCallback(() => { doSomething(id); }, [id]); 🎯 When to use useCallback: When you pass a function to a React.memo’d child Without it 👇 ➡️ A new function is created every render ➡️ React.memo becomes useless ⚠️ Common mistake: Wrapping everything in useMemo / useCallback “just in case” 💡 Reality check: Both hooks have a cost Use them only when: ✔️ You’ve identified a real performance issue ✔️ You’ve actually measured it 📌 Rule: Premature optimization ≠ good engineering #ReactJS #Hooks #JavaScript #FrontendDev
To view or add a comment, sign in
-
🚀 Controlled vs Uncontrolled Components in React — Real-World Perspective Most developers learn: 👉 Controlled = React state 👉 Uncontrolled = DOM refs But in real applications… 👉 The choice impacts performance, scalability, and maintainability. 💡 Quick Recap 🔹 Controlled Components: Managed by React state Re-render on every input change 🔹 Uncontrolled Components: Managed by the DOM Accessed via refs ⚙️ The Real Problem In large forms: ❌ Controlled inputs → Too many re-renders ❌ Uncontrolled inputs → Hard to validate & manage 👉 So which one should you use? 🧠 Real-world Decision Rule 👉 Use Controlled when: ✔ You need validation ✔ UI depends on input ✔ Dynamic form logic exists 👉 Use Uncontrolled when: ✔ Performance is critical ✔ Minimal validation needed ✔ Simple forms 🔥 Performance Insight Controlled input: <input value={name} onChange={(e) => setName(e.target.value)} /> 👉 Re-renders on every keystroke Uncontrolled input: <input ref={inputRef} /> 👉 No re-render → better performance ⚠️ Advanced Problem (Most devs miss this) 👉 Large forms with 20+ fields Controlled approach: ❌ Can slow down typing 👉 Solution: ✔ Hybrid approach ✔ Use libraries (React Hook Form) 🧩 Industry Pattern Modern apps often use: 👉 Controlled logic + Uncontrolled inputs internally Example: ✔ React Hook Form ✔ Formik (optimized patterns) 🔥 Best Practices ✅ Use controlled for logic-heavy forms ✅ Use uncontrolled for performance-critical inputs ✅ Consider form libraries for scalability ❌ Don’t blindly use controlled everywhere 💬 Pro Insight (Senior Thinking) 👉 This is not about “which is better” 👉 It’s about choosing the right tool for the problem 📌 Save this post & follow for more deep frontend insights! 📅 Day 17/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #PerformanceOptimization #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
Why do we need to call 'super(props)' in the constructor of a React component? JavaScript classes aren't magic. They are just syntactic sugar over prototypes. If you are still using (or have used) Class Components in React, you have likely typed 'super(props)' a thousand times. But do you actually know what happens if you forget it? In JavaScript, you cannot use the keyword 'this' in a constructor until you have called the parent constructor. Since your component extends 'React.Component', calling 'super()' is what actually initializes the 'this' object. If you try to access 'this.state' or 'this.props' before that call, JavaScript will throw a ReferenceError and crash your app. But why pass 'props' into it? React sets 'this.props' for you automatically after the constructor runs. However, if you want to access 'this.props' inside the constructor itself, you must pass them to 'super(props)'. If you just call 'super()', 'this.props' will be undefined until the constructor finishes execution. Most of us have moved to Functional Components where this isn't an issue. But understanding these fundamentals is what separates a developer who just writes code from one who understands the runtime. #ReactJS #Javascript #SoftwareEngineering #WebDevelopment #Coding #ProgrammingTips
To view or add a comment, sign in
-
Nobody told me this when I started React. I used it for over a year without really getting it. I could build things. Components, hooks, state — all of it. But something was always slightly off. Like, I was constantly fighting the framework instead of working with it. I'd update the state and then immediately try to read it. I'd wonder why my UI wasn't reflecting what I just changed. I'd add more useEffects, trying to force things to sync. More code. More confusion. Then I came across three characters that broke it all open for me. UI = f(state) That's it. React has one rule. Your UI is not something you control directly — it's the output of a function. You give it your data. It gives you back what the screen should look like. You don't say "update this element." You say, "here's the data." React handles the screen. I know that sounds simple. But I genuinely wasn't thinking this way. I was still mentally treating React like jQuery — find the element, change it, done. That mental model works fine for jQuery. In React it fights you every step. The moment I stopped thinking about updating UI and started thinking about describing UI — everything got easier. My components got smaller. My bugs got fewer. My useEffects stopped multiplying. Because I finally understood: my only job is to get the state right. React's job is everything else. #React #JavaScript #Frontend #ReactJS #WebDevelopment #Programming #100DaysOfCode #SoftwareDevelopment
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