React developers: stop mutating state. Use the spread operator instead. Wrong (mutates): user.role = 'admin' setUser(user) // React won't re-render! Right (creates new object): setUser({ ...user, role: 'admin' }) More React patterns: Add to array: setItems([...items, newItem]) Remove from array: setItems(items.filter(item => item.id !== removeId)) Update array item: setItems(items.map(item => item.id === targetId ? { ...item, completed: true } : item )) Merge state: setForm({ ...form, ...updates }) Nested state update: setUser({ ...user, settings: { ...user.settings, theme: 'dark' } }) Why spread over mutation: → React detects changes properly → Prevents stale closure bugs → Enables time-travel debugging → Makes state updates predictable → Follows immutability principles In React, immutability isn't optional. The spread operator makes it easy. #React #JavaScript #WebDevelopment #FrontendDev #ReactJS
React State Management: Use Spread Operator Instead of Mutation
More Relevant Posts
-
🚀 Debugging JWT Auth — A Small Mistake That Cost Me Hours Today I ran into a classic authentication issue while working with NestJS + Next.js — and it’s a good reminder of how small misunderstandings can break the whole flow. 🔍 The Problem After login, I noticed that my localStorage was saving: token: "string" Instead of an actual JWT like: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ⚠️ Clearly something was off. 🧠 The Root Cause My backend response looked like this: { "success": true, "data": { ...userDetails }, "token": "REAL_JWT_TOKEN" } But in my frontend, I made this mistake: const userData = res.data.data; localStorage.setItem("token", userData.token); // ❌ wrong 👉 The token wasn’t inside data — it was at the root level. ✅ The Fix const userData = res.data.data; const token = res.data.token; localStorage.setItem("token", token); localStorage.setItem("userData", JSON.stringify(userData)); 🔥 Debug smarter, not harder. #WebDevelopment #NestJS #NextJS #JWT #Authentication #Debugging #FullStack #JavaScript
To view or add a comment, sign in
-
One React trick that saved me hours last week: Instead of useState + useEffect to fetch data, try a custom hook. Before: 15 lines of messy fetch logic inside the component. After: One line — const { data, loading } = useProfile(userId) Clean. Reusable. Testable. This is the kind of thing that separates junior from mid-level React devs. Are you using custom hooks in your projects? Share your favorite one. #ReactJS #WebDevelopment #JavaScript #FrontendDeveloper #CodeTips
To view or add a comment, sign in
-
🚀 Mastering React Hooks . ➡️ useState batching & functional updater pattern ➡️ useEffect cleanup, dependency array pitfalls ➡️ useLayoutEffect vs useEffect - when to use each ➡️ useRef - mutable values without re-renders ➡️ useMemo — referential stability vs computation cost ➡️ useCallback - stable function references ➡️ useReducer - complex state machines ➡️ useContext - consumer re-render behaviour ➡️ custom hooks - extraction & composition patterns ➡️ uselmperativeHandle + forwardRef ➡️ useDeferredValue & UseTransition (React 18) ➡️ useld, useSyncExternalStore (React 18) 🚀 Follow Chinmay Kulkarni for more . #React #ReactJS #ReactHooks #FrontendDevelopment #JavaScript #WebDevelopment #FrontendEngineer #SoftwareEngineering #CodingInterview #InterviewPreparation #React18 #PerformanceOptimization #TechCareers #Developers #SeniorDeveloper
To view or add a comment, sign in
-
🔥 Stale Closure in React — A Common Bug You Must Know Ever faced a situation where your state is not updating correctly inside setTimeout / setInterval / useEffect? 🤯 👉 That’s called a Stale Closure --- 💡 What is happening? A function captures the old value of state and keeps using it even after updates. --- ❌ Example (Buggy Code): import { useState, useEffect } from "react"; function Counter() { const [count, setCount] = useState(0); useEffect(() => { setInterval(() => { console.log(count); // ❌ Always logs 0 (stale value) }, 1000); }, []); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); } 👉 Why? Because the closure captured "count = 0" when the effect first ran. --- ✅ Fix (Correct Approach): useEffect(() => { const id = setInterval(() => { setCount(prev => prev + 1); // ✅ always latest value }, 1000); return () => clearInterval(id); }, []); --- 🎯 Key Takeaway: Closures + async code (setTimeout, setInterval, event listeners) = ⚠️ potential stale state bugs --- 💬 Interview One-liner: “Stale closure happens when a function uses outdated state due to how closures capture variables.” --- 🚀 Mastering this concept = fewer bugs + stronger React fundamentals #ReactJS #JavaScript #Frontend #InterviewPrep #Closures #WebDevelopment
To view or add a comment, sign in
-
I’ve been using React for years… and still missed this subtle bug. While watching a tutorial, I saw a useCallback like this: const incrementHandler = useCallback(() => { if (activate) { setCount(count + 1); } }, [activate]); Looked correct. I didn’t question it. Then someone in the comments asked: 👉 “Why is count not in dependencies?” That one question changed everything. 💥 The Hidden Problem: Stale Closures React captures values at the time the function is created. So even if count updates later, your callback may still use an old value. 👉 This leads to subtle bugs that are hard to debug in production. 🧠 Common Fix (but not ideal): [activate, count] ✔️ Works ❌ But recreates function on every render ✅ Better Fix (Senior-Level): const incrementHandler = useCallback(() => { if (activate) { setCount(prev => prev + 1); //fix } }, [activate]); No stale state Stable function reference Cleaner dependencies Better performance 🔥 Real Learning Most tutorials teach what to write But real engineering is about understanding: 👉 what React is actually doing under the hood 💬 That one comment taught more than the entire video. Have you ever discovered something important just from a comment? 👇 #React #JavaScript #Frontend #WebDevelopment #SoftwareEngineering #CleanCode #ReactJS #Learning #SDE2 #Tech
To view or add a comment, sign in
-
⚡5 React “aha” moments every developer eventually has: 1️⃣ “Oh… everything re-renders.” And that’s okay — the real skill is controlling what actually updates. 2️⃣ “I don’t need this much state.” Most bugs come from storing what could’ve been derived. 3️⃣ “useEffect caused this.” At some point, you realise half your issues trace back to one hook 😅 4️⃣ “This didn’t need a library.” Overengineering hits hard when you revisit your own code. 5️⃣ “Performance is a design problem.” Not something you fix later — something you plan early. 🚀 React isn’t hard — unlearning bad patterns is. #ReactJS #ReactDevelopers #FrontendEngineering #JavaScript #WebDevelopment #ReactTips #FrontendDev #CodingLife
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 ( <> 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
-
🚀 Mastering AbortController in JavaScript/ React (A Must-Know for Modern Developers) ✅ Why should you care? ✔ Prevents memory leaks ✔ Avoids unnecessary API calls ✔ Improves performance It allows you to cancel ongoing async operations like fetch requests. 🔥 React Use Case: useEffect(() => { const controller = new AbortController(); fetch(''https://lnkd.in/d5dTeXqf'', { signal: controller.signal }) .then(res => res.json()) .then(setData) .catch(err => { if (err.name !== 'AbortError') console.error(err); }); return () => controller.abort(); // cleanup }, []); Always clean up API calls in useEffect — especially in React Strict Mode, where effects run twice in development. Follow for more 🚀 Chinmay Kulkarni #javascript #webdevelopment #frontend #reactjs #reactdeveloper #coding #programming #developers #softwareengineering #tech #interviewprep #100daysofcode #learninpublic #reactperformance #asyncjavascript
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
-
-
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
-
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