Why setState(prev => …) Exists (And When You MUST Use It) ⚛️ Ever written this and expected +2? setCount(count + 1); setCount(count + 1); But React gave you +1 😵💫 React isn’t broken. Your mental model is. What’s actually happening 👇 Remember this rule: Each render sees its own snapshot of state 📸 In that render: count has one fixed value Both updates read from the same snapshot So React sees: setCount(0 + 1); setCount(0 + 1); ➡️ Result: 1, not 2 Why the functional updater exists 🧠 Now look at this: setCount(prev => prev + 1); setCount(prev => prev + 1); This time, React does this internally: First update → prev = 0 → 1 Second update → prev = 1 → 2 Why? Because the updater function: Runs after React processes the queue Always receives the latest state, not a stale snapshot When you MUST use prev => … ✅ Use the functional updater whenever: The next state depends on the previous state You’re doing multiple updates in a row Updates happen inside async code (setTimeout, promises, events) 💡 The real takeaway setState(value) says: “Set state to this value” setState(prev => next) says: “Calculate the next state from the latest reality” If React state feels confusing, it’s usually because you’re thinking in variables — not renders. 💬 Question for you: When did this bug first bite you? #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #SoftwareEngineering #CodingBlockHisar
React setState prev => function explained
More Relevant Posts
-
Why This useEffect Runs More Than You Expect ⚛️ Ever written this and thought React was misbehaving? useEffect(() => { fetchData(); }, [fetchData]); The effect runs again… and again… 😵💫 React isn’t buggy. It’s being very precise. What React actually sees 👇 React reads this as: “Run this effect after every render where the reference of fetchData changes.” Not when the logic changes. Not when the output changes. Only when the reference changes. Here’s the hidden gotcha 🧠 In JavaScript, functions are objects. So if fetchData is defined inside your component: const fetchData = () => { // API call }; A new function is created on every render. From React’s perspective: prevFetchData !== nextFetchData // true ➡️ Dependency changed ➡️ Effect runs again Even if the function looks identical. This isn’t a React quirk ❌ It’s a design choice. React avoids deep comparisons to stay: Fast Predictable Consistent Guessing here would cause far worse bugs. 💡 The takeaway If useEffect feels “random”, it usually isn’t. Your dependencies are changing, even when your values aren’t. Once you think in references instead of values, useEffect finally makes sense. 💬 Question for you: Which dependency caused your most confusing useEffect bug? #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #CodingBlockHisar #MERN #Hisar
To view or add a comment, sign in
-
-
React stale state is not a bug. It’s us (and closures). I used to think React was “randomly” giving me old state. Turns out, it wasn’t React at all. In JavaScript, when a function is created, it freezes the values around it. That’s a closure. Whatever the state was at that moment — that’s what the function remembers. React just makes this more obvious. Every render creates a new version of your functions. But if you write useEffect(() => { ... }, []), you’re basically saying: “Hey React, keep using the first version forever.” So yeah — your effect runs, your handler fires… but it’s talking to state from the past. That’s the “stale closure” everyone trips over. For years we’ve dealt with this by: tweaking dependency arrays throwing values into useRef or just disabling the linter and moving on Recently, I’ve been liking the direction of useEffectEvent — it lets an effect run when it should, but still read the latest state without hacks. Big takeaway for me: If your hook is ignoring dependencies, it’s not optimized — it’s just outdated. Curious how others are handling this in real codebases 👇 Still useRef, or trying newer patterns? P.S : For more information on this topic , please read out my blog at medium https://lnkd.in/gDY6ZSgf #React #JavaScript #Frontend #Engineering
To view or add a comment, sign in
-
-
⚛️ When NOT to Use React Hooks React Hooks are powerful, but using them everywhere is not always the best choice. While building and refactoring components, I learned that knowing when not to use a hook is just as important as knowing how to use one. Here are some real cases where I avoid hooks: ❌ Don’t use useEffect for derived data If a value can be calculated from props or state, it doesn’t belong in useEffect. ❌ Don’t use useState for static values Constants and fixed values don’t need a state. ❌ Don’t use useMemo or useCallback prematurely Optimization hooks should solve real performance issues—not be added by default. ❌ Don’t use useRef to control UI Refs are for storing mutable values, not for triggering re-renders. ❌ Don’t add hooks just because you can Cleaner logic always beats more hooks. ✨ Key lesson: Good React code is not about using more hooks — it’s about writing simpler, more predictable components. How do you decide when a hook is really needed? #React #ReactHooks #WebDevelopment #JavaScript #Frontend #CleanCode #LearningJourney
To view or add a comment, sign in
-
-
React State Is a Snapshot — Not a Variable (A Concept Every React Dev Should Know) One of the most misunderstood concepts in React is that state is a snapshot in time, not a mutable variable. When React renders a component, it gives you a snapshot of: props state event handlers That snapshot is fixed for that render. setCount(count + 1); setCount(count + 1); setCount(count + 1); You might expect count to increase by 3 — but it doesn’t. Why? Because all three updates read the same snapshot of count. The Correct Mental Model State updates are queued React re-renders later with a new snapshot Code inside the same render never sees updated state The Fix: Functional Updates setCount(prev => prev + 1); setCount(prev => prev + 1); setCount(prev => prev + 1); Now React applies each update to the latest value, not the old snapshot. Why This Matters Understanding state as a snapshot helps you: Avoid stale state bugs Write predictable event handlers Fix issues with async logic, debouncing, and batching Reason better about concurrent rendering in React 18+ Key Takeaway State doesn’t change inside a render. React gives you a snapshot — and the next render gives you a new one. Once this clicks, many “weird” React bugs suddenly make sense. #ReactJS #Frontend #JavaScript #WebDevelopment #ReactHooks #React18
To view or add a comment, sign in
-
🚨 Rules of Hooks (and the Common Mistakes We Still Make) 🚨 React Hooks are powerful — but only if used correctly. Breaking the Rules of Hooks can lead to unexpected bugs, broken state, and hard-to-debug issues. Let’s break it down 👇 ✅ The 2 Golden Rules of Hooks 🔹 1. Call Hooks only at the top level ❌ Don’t call Hooks inside loops, conditions, or nested functions ✔ Always call them at the top of your component or custom Hook Why? React relies on the order of Hooks to manage state correctly. // ❌ Wrong if (isLoggedIn) { useEffect(() => {}, []); } // ✅ Correct useEffect(() => { if (isLoggedIn) {} }, [isLoggedIn]); 🔹 2. Call Hooks only from React functions ❌ Not inside normal JS functions ✔ Only inside: - Functional Components - Custom Hooks ⚠️ Common Hook Violations Developers Make 🚫 Conditional useEffect or useState 🚫 Calling Hooks inside callbacks or event handlers 🚫 Using Hooks inside class components 🚫 Forgetting dependencies in useEffect 🛠 Best Practices to Avoid Issues ✔ Extract reusable logic into custom Hooks ✔ Always think in terms of render cycles ✔ Treat Hooks as declarative logic, not utilities 💡 Remember: Hooks are not just functions — they are part of React’s internal state system. Mastering the Rules of Hooks = fewer bugs + cleaner code + better interviews 🚀 #ReactJS #Hooks #FrontendDevelopment #JavaScript #WebDevelopment #MERN #ReactHooks #CleanCode #CodingTips #DeveloperMistakes #SoftwareEngineering #LearningReact #FrontendTips
To view or add a comment, sign in
-
Why most React developers misunderstand useEffect It's not a lifecycle method. It's not componentDidMount in disguise. And it's definitely not the place for derived state. useEffect is synchronization with an external system. 🔍 The mental model: useEffect = "After React commits to the screen, do this side effect" The dependency array = "Only re-run when THESE values differ" Cleanup function = "Before re-running OR unmounting, clean up" Common pitfall I see: JavaScript // ❌ Wrong: Using useEffect for computed values useEffect(() => { setFullName(`${firstName} ${lastName}`); }, [firstName, lastName]); // ✅ Right: Derived state should be... just stateless computation const fullName = `${firstName} ${lastName}`; useEffect is for: API calls Subscriptions Manual DOM manipulation Analytics/logging Not for: Things you can calculate during render. What's your useEffect horror story? Drop it below 👇 #ReactJS #JavaScript #FrontendEngineering #WebDev #CleanCode
To view or add a comment, sign in
-
One practice a day keeps the bugs away. Vercel’s React best practices might be the most useful release of 2026 so far. Not because they’re new. But because they expose What most React code gets wrong. "I learned this the hard way. I was shipping features fast. Components everywhere. Hooks everywhere." And still: - Random re-renders - State bugs I couldn’t explain - Performance issues that felt “invisible” You tried the usual fixes. More memo. More abstraction. More libraries. It only made things worse. The problem wasn’t React. It was how you was using it. Here’s the core idea they push: Treat React like a system. Not a dumping ground. The result? Less debugging. Less mental load. More confidence when shipping. The takeaway (steal this): If you want fewer bugs in React: 1. Follow conventions before abstractions 2. Respect the render lifecycle 3. Push work to the server when possible 4. Optimize after correctness One practice a day. That’s all it takes. So stop skimming best practices. Start injecting them into your code’s veins. Save this. Bookmark it. Share it with a React dev who’s tired of chasing ghosts. #react #javascript #web
To view or add a comment, sign in
-
-
⚡ React isn't faster because it's smarter. It's faster because it's lazy. We hear the word "Reconciliation" thrown around in React interviews, but what does it actually mean? Here is the truth: Updating the Real DOM is slow. Extremely slow. 🐢 React’s goal is to touch the Real DOM as little as possible. How Reconciliation Works (The 3-Step Dance): - Render Phase: When state changes, React creates a new Virtual DOM tree. This is just a lightweight JavaScript object—it's fast and cheap to create. - The "Diffing" Phase: React compares the New Virtual DOM with the Old Virtual DOM. It plays a game of "Spot the Difference." "Did the parent change?" -> No. "Did the first child change?" -> No. "Did the text in the second child change?" -> YES! 🚨 - Commit Phase: React updates the Real DOM, but only changes that specific text node. It leaves the rest of the page alone. The "Key" Prop Mystery 🔑 Why does React yell at you for missing key in lists? Without keys, if you insert an item at the top of a list, React thinks every single item changed and re-renders them all. With unique keys, React says: "Oh, item #100 just moved to the top. I'll just move that one node." Reconciliation is the art of doing the bare minimum. And in software performance, laziness is a virtue. #ReactJS #Frontend #WebDevelopment #Reconciliation #Performance #Javascript #CodingInterview
To view or add a comment, sign in
-
-
💡 Do you really understand useEffect in React? In React, not everything is about rendering. Fetching data from an API, manipulating the DOM, or using setTimeout are all side effects — and that’s exactly what useEffect is for. 👉 There are 3 main ways to use useEffect: 🔹 Without a dependency array Runs on every render 🔹 With an empty array [] Runs only once, when the component mounts Perfect for initial API calls 🔹 With dependencies [state] Runs only when that specific state changes Great for reacting to controlled updates (theme, language, data, etc.) ⚠️ Don’t forget about cleanup If you add listeners, intervals, or timeouts, clean them up to avoid memory leaks. ✨ Mastering useEffect is key to writing predictable, performant, and professional React code. #ReactJS #FrontendDevelopment #JavaScript #WebDev #Hooks #CleanCode #ProgrammingTips
To view or add a comment, sign in
-
I recently revisited the React countdown timer. It reminded me of a mistake many of us have made at least once. Two common problems with timers in React - Memory leaks - Stale state caused by JavaScript closures The closure problem: When we create setInterval, the callback captures variables at creation time. So setInterval(() => { setRemainingMs(remainingMs - 1000) }, 1000) This looks okay, but it is incorrect. Because remainingMs inside a closuer is frozen. The interval keeps the old value even after React re-renders. So this leads to - Frozen timers - Skipped seconds - Incorrect UI state The correct fix: use functional state update: setRemainingMs(prev => Max.max(prev-1000, 0)) Preventing Memory Leaks: If we create something in useEffect (intervals, listeners, subscriptions), we must clean it up: return () => clearInterval(interval) Otherwise, the timer keeps running even after the component unmounts. How I remember: - If state depends on previous state -> use functional updates - If I create side effects -> I must clean them up So, React did not break my timer; JavaScript closures did, React just made them visible. If this saved you from a future bug, it was worth sharing #React #JavaScript #Frontend #WebDevelopment #CleanCode #development #devnote
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