🧠 A React Mistake That Looks Right (Until It Doesn’t) This code works. No errors. No warnings. And yet… it causes bugs. setCount(count + 1); setCount(count + 1); At first glance, it looks correct. But React doesn’t update state immediately. Both lines read the same old value. So instead of +2, you get +1. ✅ The correct approach setCount(prev => prev + 1); setCount(prev => prev + 1); Now React always uses the latest state. 🧠 What’s really happening State updates are queued React may batch them together Direct updates can become stale This is why functional updates exist. 🎯 Why interviewers love this concept Because it shows you understand: Asynchronous state updates Batching behavior Real-world React bugs Not just syntax. 📌 One rule to remember If your new state depends on the previous state, always use the functional form. #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #CleanCode #LearningInPublic
React State Update Gotcha: Functional Updates
More Relevant Posts
-
The JavaScript "this" Trap 🪤🔥 The Puzzle: What is the output? 🤔 const obj = { name: "JS", getName() { console.log(this.name); } }; const fn = obj.getName; fn(); Output: undefined Why? 🧠 In JavaScript, this depends on HOW a function is called, not where it is written. Lost Context: const fn = obj.getName only copies the function reference. Standalone Call: When you call fn(), there is no object (no dot) before the function. Global Context: It now runs in the Global Context (window object). Since window.name is not "JS", it returns undefined. How to Fix? 🛠️ ✅ Use .bind(): const fn = obj.getName.bind(obj); ✅ Use .call(): fn.call(obj); ✅ Use Arrow Functions: They inherit this from the surrounding scope. Interview Tip: 💡 Always check the "Call Site." No dot before the function call (like fn()) usually means this is lost! #JavaScript #CodingTips #365DaysOfCode #InterviewPrep #WebDev #FullStack #mern #react #node
To view or add a comment, sign in
-
DAY 20 OF POSTING REACT CONTENT ⚛️ WHAT DOES await REALLY DO? 🤔 await tells JavaScript: 👉 “Wait here until the Promise finishes.” It pauses the function until the result is ready. Example: async function getData() { const data = await fetchData(); console.log(data); } The code waits for fetchData() before moving to the next line. Cleaner than .then() Easier to read Same result #ReactJS #JavaScript #AsyncAwait #Promises #FrontendDevelopment #LearnInPublic #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
-
🚀 React Hands-on Series #4 ⏳ Problem Statement: Debounced Search Input Ever noticed how search bars don’t fire on every keystroke? That’s called debouncing — and today you’re building it. 🎯 Your Task: Create a search input with the following behavior: ✅ Input field ✅ User types normally ✅ Show the typed value only after 1000ms delay #React #FrontendDevelopment #JavaScript #PerformanceOptimization #BuildInPublic #ReactJS #CodingChallenge
To view or add a comment, sign in
-
-
💡 𝗧𝗶𝗽 𝗼𝗳 𝘁𝗵𝗲 𝗗𝗮𝘆 — 𝗥𝗲𝗮𝗰𝘁 𝗗𝗶𝗱 𝘆𝗼𝘂 𝗸𝗻𝗼𝘄? In React, 𝘀𝘁𝗮𝘁𝗲 𝘂𝗽𝗱𝗮𝘁𝗲𝘀 𝗶𝗻𝘀𝗶𝗱𝗲 𝗲𝘃𝗲𝗻𝘁 𝗵𝗮𝗻𝗱𝗹𝗲𝗿𝘀 𝗮𝗿𝗲 𝗯𝗮𝘁𝗰𝗵𝗲𝗱, meaning multiple "setState" calls may result in a 𝘀𝗶𝗻𝗴𝗹𝗲 𝗿𝗲-𝗿𝗲𝗻𝗱𝗲𝗿. Why it matters: - Improves performance automatically - Explains why consecutive state updates don’t always update immediately - Encourages writing state updates that depend on previous state using the functional form Understanding batching helps you write more predictable React code. #React #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #SoftwareEngineering #CodingTips #PerformanceOptimization #FullstackDeveloper
To view or add a comment, sign in
-
-
React is killing complex logics day by day more better code optimization better performance new React pattern (use() + async support): #ReactJS #FrontendDevelopment #WebPerformance #LearningInPublic #JavaScript #Consistency
To view or add a comment, sign in
-
-
🧩 JavaScript Output-Based Question (this + setTimeout) ❓ What will be the output? 👉 Comment your answer below (Don’t run the code ❌) Output: undefined 🧠 Why this output comes? (Step-by-Step) 1️⃣ print() is called as a method obj.print(); So inside print, this correctly refers to obj. 2️⃣ But inside setTimeout… setTimeout(function () { console.log(this.name); }, 0); The callback is a regular function, not a method of obj. When it executes: • this does NOT refer to obj • In non-strict mode → this points to the global object • In strict mode → this is undefined Either way: this.name → undefined 3️⃣ The key mistake ❌ Assuming this is preserved automatically in async callbacks 🔑 Key Takeaways ✔️ this depends on how a function is called ✔️ setTimeout callbacks lose object context ✔️ Use arrow functions or .bind() to fix this ✔️ This bug appears frequently in real projects #JavaScript #ThisKeyword #AsyncJavaScript #setTimeout #InterviewQuestions #FrontendDeveloper #MERNStack #ReactJS
To view or add a comment, sign in
-
-
Most performance issues come down to one thing: Unnecessary Re-renders. React is fast, but it’s not magic. If you don't manage how and when your components update, your DOM will pay the price. In this carousel, I break down: The 4 core triggers of a re-render. The 'Waterfall Effect' in parent-child relationships. How to stabilize your code using professional patterns." #ReactJS #WebDevelopment #JavaScript #FrontendPerformance #MERNStack #ReactHooks #ZhairAhmad #SoftwareEngineering
To view or add a comment, sign in
-
frameworks and libraries is all about syntax, the real deal is knowing what powers them... useEffect and useState are dangerous syntax to someone who doesn't understand how window loaded and DomContent event listeners work in pure javaScript... Axios is great but if you dont know how the fetch API works, the you would struggle to undertstand how the browser handles http errors... Knowing the fundamentals isn't about going back to the stone age, its what you need to build with confidence. #reactjs #frontend #javaScript
To view or add a comment, sign in
-
-
🚀 JavaScript Interview Question (Event Loop + Async/Await) What will be the output of this code? 🤔 async function foo() { console.log('A'); setTimeout(() => console.log('B'), 0); await Promise.resolve(); console.log('C'); } foo(); console.log('D'); 🧠 Think carefully before answering. This question tests your understanding of: ✅ Call Stack ✅ Microtask Queue ✅ Macrotask Queue ✅ async/await behavior ✅ Event Loop 👇 Drop your answer in the comments (in order). No cheating. No running the code 😄 I’ll share the explanation in the next post. #JavaScript #FrontendDevelopment #ReactJS #WebDevelopment #AsyncAwait #EventLoop #CodingInterview #SoftwareEngineering
To view or add a comment, sign in
-
Schema validation is a critical part of building secure and reliable APIs. Here’s a side-by-side comparison of Express Validator, Joi, and Zod with practical examples to help you understand the differences in syntax and structure. Which one do you prefer in your Node.js projects — Express Validator, Joi, or Zod? #NodeJS #BackendDevelopment #JavaScript #WebDevelopment #APIs
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