🚨 React Interview Question That Confuses 90% Developers Let’s test your React fundamentals 👇 import { useState } from "react"; export default function App() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); setCount(count + 2); setCount(count + 3); console.log(count); } return ( <> <h1>{count}</h1> <button onClick={handleClick}>Click</button> </> ); } 👉 What will be the output? 1️⃣ Console output? 2️⃣ Final UI value? ⚡ Bonus: Why doesn’t it become 3 (or even 6)? 👇 Think before reading the answer 👇 — — — — — — — — — — — — ✅ Answer Console → 0 UI → 3 🧠 Why? React batches state updates and treats them as async. All setCount calls use the same stale value (count = 0). So internally: 0 + 1 = 1 0 + 2 = 2 0 + 3 = 3 ✅ (last update wins) 🔥 Correct way (if you want cumulative updates): setCount(prev => prev + 1); setCount(prev => prev + 1); setCount(prev => prev + 1); 👉 Now React updates sequentially → Final = 3 💬 Takeaway: • State updates are async • React batches updates • Avoid stale values • Use functional updates when chaining Did you get it right? 👀 #ReactJS #FrontendInterview #JavaScript #ReactHooks #FrontendDeveloper
React Interview Question: State Update Batching and Stale Values
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 ( <> 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
To view or add a comment, sign in
-
React Interview Question: How do you handle long-running tasks in React without blocking the UI? In React, heavy computations or long-running tasks can freeze the UI because JavaScript runs on a single thread. Here are some effective techniques to handle long-running tasks without blocking the UI: 🔹 1. Use Web Workers (Best for heavy computations) Run expensive logic in a separate thread so the main UI thread stays free. This is Ideal for Data processing , Large calculations and Parsing big files 🔹 2. Break Work into Smaller Chunks Instead of one big blocking task, split it using: - setTimeout - requestIdleCallback This allows the browser to update the UI between tasks. 🔹 3. Use React Features (Concurrent UI) React provides tools to keep UI smooth: - useTransition (mark updates as non-urgent) - useDeferredValue (delay expensive rendering) 🔹 4. Memoization useMemo is used to cache expensive calculations useCallback is used to prevent unnecessary re-renders 🔹 5. Move Work to Backend If the computation is too heavy, move it to the backend: - offload processing to APIs - process tasks asynchronously on the server 🔹 6. Lazy Loading & Code Splitting Load only what’s needed using: - React.lazy - Suspense Connect/Follow Tarun Kumar for more tech content and interview prep #ReactJS #Frontend #WebDevelopment #JavaScript #InterviewPrep
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
-
𝐀𝐝𝐯𝐚𝐧𝐜𝐞𝐝 𝐑𝐞𝐚𝐜𝐭 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🚀 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
-
-
Day 23: Higher Order Components (HOC) in React If you want to write reusable and scalable React code, you must understand this concept: 👉 Higher Order Components (HOC) This is also a popular React interview question. 📌 What is a Higher Order Component? A Higher Order Component (HOC) is a function that: ✅ takes a component as input ✅ returns a new enhanced component as output In simple words: 👉 HOC = Component that wraps another component to add extra features 📌 Why do we use HOC? Sometimes we want to reuse the same logic across multiple components like: • Authentication check • Logging • Loading spinner • Permissions • Data fetching Instead of repeating code, we use HOC. 📌 Example of HOC function withLogger(WrappedComponent) { return function EnhancedComponent(props) { console.log("Component Rendered:", WrappedComponent.name); return <WrappedComponent {...props} />; }; } 📌 Using the HOC function Profile() { return <h1>Profile Page</h1>; } export default withLogger(Profile); Now every time Profile renders, it logs automatically. 📌 Key Point ✅ HOC does not modify the original component It creates a new component with added functionality. 📌 Real-world Example Many libraries use HOC internally, like: • Redux (connect) • Authentication wrappers • Role-based UI access 📌 Interview Line 👉 HOC is used for code reusability and logic sharing in React. #ReactJS #HOC #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
𝐖𝐡𝐲 𝐃𝐨 𝐖𝐞 𝐔𝐬𝐞 𝐂𝐥𝐨𝐬𝐮𝐫𝐞𝐬 𝐢𝐧 𝐑𝐞𝐚𝐜𝐭 𝐉𝐒? 🤔 Closures are one of the most important concepts in JavaScript… and React uses them everywhere. But many developers don’t realize it 👇 What is a closure? A closure is when a function remembers the variables from its outer scope even after that scope has finished execution. How React uses closures 👇 🔹 Event Handlers Functions like onClick capture state values at the time they are created 🔹 Hooks (useState, useEffect) Hooks rely on closures to access state and props inside functions 🔹 Async operations (setTimeout, API calls) Closures hold the state values when the async function was created Example 👇 const [count, setCount] = useState(0); const handleClick = () => { setTimeout(() => { console.log(count); }, 1000); }; What will this log? 🤔 It logs the value of count at the time handleClick was created This is why we sometimes face “stale closure” issues ⚠️ Why this matters? Understanding closures helps you: ✔ Debug tricky bugs ✔ Avoid stale state issues ✔ Write better React logic Tip for Interview ⚠️ Don’t just define closures Explain how they behave in React That’s what interviewers look for Good developers use React. Great developers understand how it works under the hood. 🚀 #ReactJS #JavaScript #Closures #FrontendDeveloper #WebDevelopment #ReactInterview #CodingInterview #SoftwareDeveloper
To view or add a comment, sign in
-
-
𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐂𝐥𝐨𝐬𝐮𝐫𝐞 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 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
-
-
💪 Day 3/30 — Next.js & MERN Stack Interview Prep Q: What is useEffect and how do you handle side effects in Next.js? 🏂 Short Answer: useEffect is a React hook that lets you run side effects — like data fetching, subscriptions, or DOM manipulation — after a component renders. 🔍 The Full Answer: useEffect(() => { // your side effect here return () => { // cleanup (optional) }; }, [dependencies]); The dependency array controls WHEN it runs: [] → runs once on mount [value] → runs when value changes no array → runs after every render ⚠️ ⚡ In Next.js specifically — this matters: useEffect only runs on the client side. So in Next.js App Router, if you're using useEffect, your component must be marked as: "use client"; Server Components can't use useEffect at all. 🧠 A common interview trap: useEffect(() => { fetch("/api/data") .then(res => res.json()) .then(data => setData(data)); }, []); // ✅ runs once Interviewers love asking: "What happens if the component unmounts before the fetch completes?" Answer: You get a memory leak. Fix it with a cleanup flag or AbortController: useEffect(() => { const controller = new AbortController(); fetch("/api/data", { signal: controller.signal }) .then(res => res.json()) .then(data => setData(data)) .catch(err => { if (err.name !== "AbortError") console.error(err); }); return () => controller.abort(); }, []); 🏌️ Key Takeaways: useEffect = side effects after render Always think about the dependency array In Next.js App Router → needs "use client" Clean up async effects to avoid memory leaks Follow for Day 4 tomorrow! 🔔 #NextJS #React #JavaScript #WebDevelopment #InterviewPrep #MERN #30DayChallenge #FrontendDeveloper
To view or add a comment, sign in
-
𝗘𝘀𝘀𝗲𝗻𝘁𝗶𝗮𝗹 𝗥𝗲𝗮𝗰𝘁𝗝𝗦 𝗖𝗼𝗻𝗰𝗲𝗽𝘁𝘀 𝗳𝗼𝗿 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄𝘀 React remains a core skill for modern frontend roles. Strong understanding goes beyond memorization—it’s about applying concepts effectively. 𝗞𝗲𝘆 𝗮𝗿𝗲𝗮𝘀 𝘁𝗼 𝗳𝗼𝗰𝘂𝘀 𝗼𝗻: • How React works • Component-based architecture • Virtual DOM & performance • Real-world application patterns Credit: owner Follow Alpna P. for more related content! 🤔 Having Doubts in technical journey? 🚀 Book 1:1 session with me : https://lnkd.in/gQfXYuQm 🚀 Subscribe and stay up to date: https://lnkd.in/dGE5gxTy 🚀 Get Complete React JS Interview Q&A Here: https://lnkd.in/d5Y2ku23 🚀 Get Complete JavaScript Interview Q&A Here: https://lnkd.in/d8umA-53 #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #InterviewPrep #SoftwareEngineering
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
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
Keep sharing