You think this React code will increment the counter to 2? Maga Look again.👇🐘🐘🐘 function App() { const [count, setCount] = useState(0); const handleClick = () => { setTimeout(() => { setCount(count + 1); }, 1000); setCount(count + 1); }; return ( <> <p>{count}</p> <button onClick={handleClick}>Click</button> </> ); } Most developers say: 👉 “First +1 immediately, then +1 after 1 second → final = 2” ❌ Wrong 🧠 What actually happens setCount(count + 1) → updates to 1 setTimeout callback runs later… But it uses stale count = 0 (closure!) 👉 So it sets 1 again 🎯 Final Result Count = 1, not 2 🚨 The real problem This is not a React bug This is a JavaScript closure + event loop problem Functions capture old state Async callbacks don’t magically get updated values React state is snapshot-based, not live ✅ Fix setCount(prev => prev + 1); ✔ Always use functional updates when state depends on previous value ✔ Works correctly with async (timeouts, promises, events) 💡 Takeaway If your mental model is: 👉 “state updates automatically everywhere” You’ll ship bugs. If your mental model is: 👉 “state is captured at execution time” You’ll write predictable systems. This is the difference between writing code that works… and code that scales in production. USE prev maga 😍 setCount(prev => prev + 1); 🐘🐘🐘 #ReactJS #JavaScript #Frontend #WebDevelopment #Debugging #EventLoop
React State Update Issue: Closure and Event Loop Problem
More Relevant Posts
-
I struggled with this React concept more than I expected… 👇 👉 Why are my API calls running twice? ⚙️ What you’ll notice You open your network tab and suddenly see this: api/me → called twice api/roles → called twice api/permissions → called twice Just like in the screenshot 👇 Same request, duplicated… again and again. ⚙️ What’s actually happening In React (development mode), if your app is wrapped in Strict Mode, React will run effects twice on purpose. useEffect(() => { fetch("/api/users") .then(res => res.json()) .then(setUsers); }, []); Even though it looks like it should run once… it doesn’t (in dev). 🧠 What’s going on under the hood React basically does a quick cycle: mount → unmount → remount Why? To catch hidden side effects To check if cleanup is handled properly To make sure your logic doesn’t break on re-renders So if your API call runs twice, React is just making sure your code can handle it. 💡 The important part This only happens in development Production behaves normally (runs once) Your side effects should be safe to run multiple times 🚀 Final thought If your network tab looks “noisy” like the screenshot, it’s not React being broken — it’s React being careful. And once you understand this, debugging becomes a lot less confusing. #React #Frontend #JavaScript #WebDevelopment #ReactJS #SoftwareEngineering
To view or add a comment, sign in
-
Why does the same React component behave differently on each render? You wrote it once.... Same code. Same props. But sometimes: → It shows different data → It lags → It resets Looks like a bug… But often, it’s just React doing its job. 𝗛𝗲𝗿𝗲’𝘀 𝘄𝗵𝗮𝘁’𝘀 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗵𝗮𝗽𝗽𝗲𝗻𝗶𝗻𝗴: Every time a parent component re-renders — every child inside it re-renders too. React re-runs the component function to check what changed. Even if props look the same. 𝗛𝗼𝘄 𝘁𝗼 𝘁𝗲𝗹𝗹 𝗥𝗲𝗮𝗰𝘁 𝘁𝗼 𝘀𝗸𝗶𝗽 𝗿𝗲-𝗿𝗲𝗻𝗱𝗲𝗿: Wrap your component in React.memo() const Card = React.memo(({ name }) => { return <div>{name}</div> } Now React skips re-rendering Card unless its props actually change. Same component. Smarter behavior. 𝗥𝗲-𝗿𝗲𝗻𝗱𝗲𝗿 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 𝘄𝗵𝗲𝗻: → State changes → Props change → Parent re-renders `React.memo` stops the third one (when props are stable). 𝗣𝗿𝗼 𝘁𝗶𝗽: If memo isn't skipping, check if you're passing new functions/objects/arrays every time — those break the shallow compare. Fix with 𝘶𝘴𝘦𝘊𝘢𝘭𝘭𝘣𝘢𝘤𝘬/𝘶𝘴𝘦𝘔𝘦𝘮𝘰. Understanding this is the difference between “it works” and “it scales.” Save this — next time re-renders confuse you, you’ll know exactly why. Have you ever had unexpected re-renders break your app? Drop it below 👇 Follow for more React concepts explained simply. #reactjs #webdevelopment #javascript #MERN
To view or add a comment, sign in
-
-
The Importance of Code Splitting in Frontend Apps As frontend applications grow larger, loading all JavaScript at once can significantly slow down performance. Code splitting is a technique that allows developers to break their application into smaller chunks that can be loaded on demand. This means users only download the code they need for the current page, improving load times and overall user experience. Frameworks like Next.js make code splitting easier by automatically splitting code based on routes. When a user navigates to a new page, only the necessary code for that page is loaded. This reduces the initial load time and ensures that applications remain fast even as they grow in complexity. Code splitting is especially important for users on slower networks or mobile devices. By reducing the amount of data transferred, developers can create more accessible and efficient applications. When combined with other optimization techniques such as lazy loading and caching, code splitting becomes a powerful tool for improving frontend performance. Question for discussion: Have you implemented code splitting in your projects, and did it improve performance? #FrontendDevelopment #JavaScript #Nextjs #WebPerformance #Programming
To view or add a comment, sign in
-
-
26 questions. The difference between knowing React on paper and surviving a real production codebase. Here are the 26 questions categorized by the depth of experience required: Level 1: The Foundations => How does React’s rendering process work? => What’s the difference between state and props? => What are hooks, and why were they introduced? => What are controlled vs uncontrolled components? => When would you use refs? => How do you handle forms and validations? Level 2: State & Logic => When should you lift state up? => How do you manage complex state in an application? => When would you use useState vs useReducer? => How do useEffect dependencies work? => How do you handle API calls (loading, error, success states)? => How do you manage shared state across components? => Context API vs Redux — when would you use each? Level 3: Performance & Scale => What causes unnecessary re-renders, and how do you prevent them? => What is memoization in React? => When would you use React.memo, useMemo, and useCallback? => How do you structure a scalable React application? => How do you optimize performance in large-scale apps? => What tools do you use to debug performance issues? => How do you secure a React application? => How do you test React components effectively? Level 4: The War Stories => Have you faced an infinite re-render issue? How did you fix it? => Tell me about a complex UI you built recently. => How did you improve performance in a React app? => What’s the hardest bug you’ve fixed in React? => How do you handle 50+ inputs in a single form without lag? Syntax is easy to Google. Deep understanding is hard to fake. #ReactJS #FrontendDevelopment #TechInterviews #JavaScript #WebDevelopment #Developers
To view or add a comment, sign in
-
⚛️ How React Re-Renders Components (Simple Explanation) While working with React, one thing I was always curious about was: 👉 What actually happens when a component re-renders? Here’s a simple way I understand it 👇 🔹 What triggers a re-render? A component re-renders when: • state changes • props change • parent component re-renders 🔹 What happens during a re-render? React doesn’t directly update the DOM. Instead: 1️⃣ It creates a new Virtual DOM 2️⃣ Compares it with the previous version (diffing) 3️⃣ Updates only the changed parts in the real DOM This process is called Reconciliation 🔹 Why this matters Understanding this helps you: ✅ avoid unnecessary re-renders ✅ optimize performance ✅ write more efficient components 🔹 Common mistake A parent re-render can cause all child components to re-render — even if their data hasn’t changed. That’s where optimizations like: • React.memo • useMemo • useCallback become useful. 💡 One thing I’ve learned: React is fast — but understanding how it works internally helps you make it even better. Curious to hear from other developers 👇 What strategy do you use to prevent unnecessary re-renders? #reactjs #frontenddevelopment #javascript #webdevelopment #softwareengineering #developers
To view or add a comment, sign in
-
-
Some of the hardest React bugs I’ve seen weren’t actually inside React. They were happening somewhere in between. Between the event loop and the render cycle. You know the kind of bug. Everything looks correct. State updates are there. Handlers are wired properly. The logic makes sense. And yet… the UI shows stale data. Something flickers for a split second. It works fine locally, but breaks under real user interaction. Those are the bugs that make you question your sanity a bit. What’s really going on is this. We tend to think of React and JavaScript as one system. But they’re not. JavaScript runs your code - sync, promises, timeouts, all of that. React runs its own process - scheduling renders, batching updates, deciding when the UI actually updates. Most of the time, we blur that into one mental model. And most of the time it works. Until it doesn’t. That gap is where things get weird. You’ve probably seen versions of this: 🔹 You call setState and immediately get the old value 🔹 A setTimeout fires and uses stale data 🔹 A promise resolves and overwrites something newer 🔹 Everything works… until a user clicks fast enough Individually, none of this is surprising. But when it happens in a real app, it feels unpredictable. Because the problem isn’t what your code does. It’s when it runs. That’s why these bugs are so frustrating. You’re not debugging logic anymore. You’re debugging timing. The more I work on complex React apps, the more I notice this - a big part of senior frontend work isn’t just knowing hooks or patterns. It’s understanding how React’s rendering model interacts with the JavaScript runtime. Because once timing gets involved what looks correct can still be completely wrong. #reactjs #javascript #frontend #webdevelopment #softwareengineering #debugging #performance #typescript
To view or add a comment, sign in
-
🧠 Why map() in React Needs a key (Beyond Just a Warning) Most developers know this warning: “Each child in a list should have a unique key” So they do this 👇 {items.map((item, index) => ( <li key={index}>{item}</li> ))} Warning gone ✅ Problem solved ❌ 🔍 What actually happens? React uses key to track elements between renders. If you use index: 👉 React assumes position = identity ⚠️ The hidden bug const items = ["A", "B", "C"]; Now remove "A". New list: ["B", "C"] With index as key: "B" becomes index 0 React thinks it’s still "A" 👉 UI can behave incorrectly 👉 State can get mixed up ✅ Correct approach {items.map(item => ( <li key={item.id}>{item.name}</li> ))} 👉 Use a stable, unique key 🎯 Real Insight key is not for React warnings. It’s for correct UI behavior. 💥 Senior-level understanding Bad keys don’t always break immediately. They break when: Items reorder Items are removed State is attached to elements That’s why bugs feel random. #ReactJS #FrontendDevelopment #JavaScript #CleanCode #WebDevelopment #CodingTips #LearningInPublic
To view or add a comment, sign in
-
There's a page in the React docs called "You Might Not Need an Effect." I'd say it's one of the most important pages in the entire React documentation. And most developers have either never read it or read it once and moved on. The whole idea comes down to one question: is your code syncing React with something React doesn't control? A WebSocket, a browser API, a third-party library? If yes, useEffect makes sense. If no, you're probably just adding extra renders and making your code harder to follow. Some patterns worth knowing: If you're deriving a value from props or state, just calculate it during render. No state, no effect needed. If you're responding to a user action like a click or form submit, put it in the event handler. The event handler already knows what happened. The effect doesn't. If you need to reset state when a prop changes, use the key prop. React will remount the component and reset everything automatically. If you're chaining effects where one sets state and triggers another, collapse all of it into a single event handler. React batches those updates into one render. If a child is fetching data just to pass it up to a parent, flip the flow. Let the parent fetch and pass it down. The rule the docs give is honestly the clearest way I've seen it put: if something runs because the user did something, it belongs in an event handler. If it runs because the component appeared on screen, it belongs in an effect. Every unnecessary useEffect is an extra render pass, an extra place for bugs to hide, and more code for the next person to untangle. Worth a read if you haven't: https://lnkd.in/gqUr7e_S How many effects in your current codebase do you think would actually pass that test? #ReactJS #Frontend #JavaScript #WebDevelopment #CleanCode
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
-
-
🚀 useReducer in React — When useState is Not Enough As your React app grows… 👉 State becomes complex 👉 Multiple updates depend on each other 👉 Logic gets messy That’s where useReducer comes in. 💡 What is useReducer? useReducer is a hook for managing complex state logic using a reducer function. 👉 Inspired by Redux ⚙️ Basic Syntax const [state, dispatch] = useReducer(reducer, initialState); 🧠 How it works 👉 Instead of updating state directly: setCount(count + 1); 👉 You dispatch actions: dispatch({ type: "increment" }); 👉 Reducer decides how state changes: function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; default: return state; } } 🧩 Real-world use cases ✔ Complex forms ✔ Multiple related states ✔ State transitions (loading → success → error) ✔ Large components with heavy logic 🔥 Why useReducer? 👉 useState works well for simple state 👉 useReducer works better for structured logic 🔥 Best Practices (Most developers miss this!) ✅ Use when state depends on previous state ✅ Use for complex or grouped state ✅ Keep reducer pure (no side effects) ❌ Don’t use for simple state ❌ Don’t mix business logic inside components ⚠️ Common Mistake // ❌ Side effects inside reducer function reducer(state, action) { fetchData(); // ❌ Wrong return state; } 👉 Reducers must be pure functions 💬 Pro Insight (Senior-Level Thinking) 👉 useState = simple updates 👉 useReducer = predictable state transitions 👉 If your state has “rules” → useReducer 📌 Save this post & follow for more deep frontend insights! 📅 Day 20/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #StateManagement #SoftwareEngineering #100DaysOfCode 🚀
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