Your component unmounted. But your timer didn't. This is one of the most common memory leaks in React — and it leaves zero errors in the console. Here's what's happening: 𝗪𝗶𝘁𝗵𝗼𝘂𝘁 𝗰𝗹𝗲𝗮𝗻𝘂𝗽: useEffect(() => { const id = setInterval(() => { console.log('still running...'); setData(fetch()); // setting state on unmounted component }, 1000); }, []); User navigates away. Component unmounts. But the interval is still alive in memory. Still firing. Still trying to update state that no longer exists. React will warn you: "Can't perform a React state update on an unmounted component" But by then — the leak already happened. 𝗪𝗶𝘁𝗵 𝗰𝗹𝗲𝗮𝗻𝘂𝗽: useEffect(() => { const id = setInterval(() => { console.log('running...'); }, 1000); return () => clearInterval(id); // 👈 this is the cleanup }, []); The function you return from useEffect runs in two situations: → Before the effect runs again (dependency changed) → When the component unmounts Think of it as a paired contract: You start something → you are responsible for stopping it. 𝗧𝗵𝗿𝗲𝗲 𝘁𝗵𝗶𝗻𝗴𝘀 𝘁𝗵𝗮𝘁 𝗮𝗹𝘄𝗮𝘆𝘀 𝗻𝗲𝗲𝗱 𝗰𝗹𝗲𝗮𝗻𝘂𝗽: → setInterval / setTimeout → Event listeners (window.addEventListener) → WebSocket or API subscriptions If you start it in useEffect — you clean it up in the return. No exceptions. Have you ever shipped a memory leak from a missing cleanup? 👇 #ReactJS #JavaScript #WebDevelopment #Frontend #useEffect #LearnInPublic #SoftwareEngineering #TypeScript #Programming
React Memory Leak: Unmounted Component with useEffect
More Relevant Posts
-
Why I don't compare single memory snapshots in sweptJS: My first instinct: grab the latest heap reading, compare it to the previous one, flag if bigger. Also completely wrong. Garbage Collection fires whenever it wants, dropping heap by 30-40% instantly. Point-to-point comparisons either miss real leaks or false-alarm on normal bursts. The fix: Windowed Averaging Instead of comparing points, compare windows. SweptJS takes the average of the oldest 5 samples vs the newest 5, and flags if the newer window is ≥ 20% larger, a sustained trend, not a spike. And since it's relative, a 20MB jump on a 10MB heap hits very differently than on a 100MB one. But heap alone lies. DOM leaks can pile up quietly while heap numbers look fine. So SweptJS runs a second heuristic in parallel — tracking alive detached nodes via MutationObserver + FinalizationRegistry. Same windowing logic. The Decision: 🔴 Both signals → High confidence leak 🟡 Heap only → Probable closure/cache leak 🟡 DOM only → Probable DOM leak 🟢 Neither → All clear One metric lying to you. Two metrics agreeing is a pattern. I am attaching a videos of progress so far, still in middle of building a UI Moreover i am open to suggetions and ideas. #Github: https://lnkd.in/gWNHt49F #BuildInPublic #SweptJS #JavaScript #MemoryLeaks #TypeScript #ChromeExtension #Webdevelopment #development
To view or add a comment, sign in
-
🧠 React state is NOT a variable 🔍 The problem Most devs assume state updates instantly. That’s why you see: • Old values in logs • Confusing behavior in event handlers • setState not working as expected 💡 The shift State is not a variable It’s a snapshot per render 🧠 Mental model Think of React like a camera 📸 Each render = a photo • Fixed state • Fixed event handlers Once captured → it never changes ⚙️ What’s actually happening • setState → requests a new render • React stores state outside your component • Each render gets its own snapshot • Old handlers use old snapshots ⚠️ Common bug setCount(count + 1) setCount(count + 1) 👉 Both use the same snapshot ✅ Correct approach setCount(prev => prev + 1) 🚀 Practical takeaway If next state depends on previous state → use functional updates That single rule removes most “state bugs” in React #React #JavaScript #Frontend #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
-
💡 Mastering useEffect in React — Stop Guessing, Start Understanding If you’ve worked with React, you’ve probably used useEffect… and maybe struggled with it too. Here’s the simple way to think about it: 👉 useEffect lets you run side effects in your components That means anything that interacts outside the React render cycle: - API calls 🌐 - Subscriptions 🔔 - Timers ⏱️ - DOM manipulation 🧩 🔑 The 3 most important patterns: 1] Run once (on mount): useEffect(() => { console.log("Component mounted"); }, []); 2] Run when a dependency changes: useEffect(() => { console.log("Value changed"); }, [value]); 3] Cleanup (avoid memory leaks): useEffect(() => { const timer = setInterval(() => { console.log("Running..."); }, 1000); return () => clearInterval(timer); }, []); ⚠️ Common mistakes to avoid: Forgetting dependencies → leads to stale data bugs Adding unnecessary dependencies → causes infinite loops Ignoring cleanup → memory leaks & performance issues 🧠 Pro tip: If your useEffect feels complicated… it probably is. Try splitting it into smaller effects or rethinking your logic. ✨ useEffect isn’t hard — it’s just misunderstood. Once you get the mental model right, everything clicks. #React #JavaScript #WebDevelopment #Frontend
To view or add a comment, sign in
-
🥁 𝗩𝟳.𝟮.𝟬 𝗶𝘀 𝗼𝘂𝘁. 𝗧𝗵𝗶𝘀 𝗼𝗻𝗲 𝗮𝗱𝗱𝘀 𝘀𝗼𝗺𝗲𝘁𝗵𝗶𝗻𝗴 𝗽𝗲𝗼𝗽𝗹𝗲 𝗵𝗮𝘃𝗲 𝗯𝗲𝗲𝗻 𝗮𝘀𝗸𝗶𝗻𝗴 𝗳𝗼𝗿. react-infinite-scroll-component (https://lnkd.in/gZgRuSkG) has always been a drop-in component. That works great for most cases. But if you want full control over your list markup, custom wrappers, headless UI, your own loading states, you were stuck working around the component's structure. 𝗡𝗼𝘁 𝗮𝗻𝘆𝗺𝗼𝗿𝗲. 😎 𝗩𝟳.𝟮.𝟬 𝘀𝗵𝗶𝗽𝘀 𝘂𝘀𝗲𝗜𝗻𝗳𝗶𝗻𝗶𝘁𝗲𝗦𝗰𝗿𝗼𝗹𝗹, a hook that exposes the same IntersectionObserver sentinel logic as the component, but hands you back a sentinelRef to place wherever you want. Place the ref. Build your list however you want. The library handles the rest. And yes, Ankeet Maini, we heard you. 𝗩𝟳.𝟮.𝟬 𝗮𝗹𝘀𝗼 𝘀𝗵𝗶𝗽𝘀 𝗔𝗚𝗘𝗡𝗧𝗦.𝗺𝗱 𝗮𝗻𝗱 𝗹𝗹𝗺𝘀.𝘁𝘅𝘁 so Claude, Codex, Copilot, and friends know exactly how to use this library when generating code for users. 😄 𝗛𝗲𝗿𝗲’𝘀 𝘄𝗵𝗲𝗿𝗲 𝘁𝗵𝗲 𝗿𝗼𝗮𝗱𝗺𝗮𝗽 𝘀𝘁𝗮𝗻𝗱𝘀: ✅ 𝗣𝗵𝗮𝘀𝗲 𝟭 - Test suites & CI/CD (v6.1.1) ✅ 𝗣𝗵𝗮𝘀𝗲 𝟮 - React 18/19 support, tooling modernization (v7.0.0) ✅ 𝗣𝗵𝗮𝘀𝗲 𝟯 - IntersectionObserver core rewrite (v7.1.0 & v7.2.0) 🔜 𝗣𝗵𝗮𝘀𝗲 𝟰 - Accessibility & documentation npm install react-infinite-scroll-component@latest We're actively looking for contributors to help make this the best scroll library out there. Browse the open issues on GitHub, pick something that interests you, or file a new one if you think something's worth working on. 𝗘𝘃𝗲𝗿𝘆 𝗰𝗼𝗻𝘁𝗿𝗶𝗯𝘂𝘁𝗶𝗼𝗻 𝗰𝗼𝘂𝗻𝘁𝘀. 🙌🏻 #OpenSource #React #JavaScript #WebDevelopment #Maintainership #Community
To view or add a comment, sign in
-
-
Day 6 — Find Second Largest Number in an Array (JavaScript) Problem Write a function to find the second largest number in an array. Example Input: [10, 5, 8, 20] Output: 10 Approach First find the largest number, then find the largest number smaller than it. Code function secondLargest(arr){ let largest = -Infinity let second = -Infinity for(let i = 0; i < arr.length; i++){ if(arr[i] > largest){ second = largest largest = arr[i] } else if(arr[i] > second && arr[i] !== largest){ second = arr[i] } } return second } console.log(secondLargest([10,5,8,20])) Alternative Approach function secondLargest(arr){ let sorted = [...new Set(arr)].sort((a,b) => b-a) return sorted[1] } What I Learned How to track two maximum values in a single loop. #javascript #frontenddeveloper #codingpractice #webdevelopment
To view or add a comment, sign in
-
-
How do you parse MDX in Next.js with a 0 KB client bundle? 🤔 After months of development and testing, I’m incredibly proud to announce the public launch of Omni-Core (and its stable release v1.1.0)! 🎉 Historically, MDX rendering in React has always been a trade-off: either you sacrifice build speed, or you bloat the client bundle, which hurts performance. And with the arrival of React Server Components (RSC), getting complex ASTs to coexist with the JS ecosystem (Rehype/Unified) has proven to be a real sanitization headache. With Omni-Core, we tackled the problem at its root: moving everything to a native Rust engine. Here’s what’s under the hood 🛠️: 🦀 Native Rust core (napi-rs): A parser 10 to 50 times faster than in JS, using a zero-copy memory architecture to communicate with V8. ⚛️ 100% Server Components: MDX is parsed on the server and sent to the browser as pure static HTML. No parsing logic is sent to the client. 🛡️ Unified/HAST Bridge: Your favorite Rehype plugins (syntax highlighting, etc.) work natively without destroying your component metadata or LaTeX formulas. 🐍 Web & Desktop Parity: This same Rust engine powers our Python library for native rendering (PyQt5) that is strictly identical to the web version. The project is entirely open-source. If you’re interested in extreme optimization, Next.js, or Rust/V8 interoperability, feel free to check out the repo and the documentation! 👇 🔗 GitHub: https://lnkd.in/eQDiZfut 📖 Documentation: https://omni-core.org/mdx Your feedback or pull requests are welcome! And a little ⭐️ on the repo is always appreciated to support the project. #Nextjs #Rust #ReactJS #OpenSource #WebPerformance #DeveloperTools #OmniCore
To view or add a comment, sign in
-
-
useState × 4. onChange × 4. try/catch. isPending. That's the boilerplate every React form has shipped with for years. React 19 quietly deleted all of it. The new shape is two things: - An Action: an async function that takes (prevState, formData) and returns next state - useActionState(action, initial): gives you [state, formAction, isPending] And the form becomes: <form action={formAction}> What disappears: - useState for every input (uncontrolled inputs + FormData) - onChange handlers - gone entirely - try/catch in the component (the Action returns success or error) - Manual isPending tracking (the hook hands it to you) What you write instead: - One async function (the Action) - One hook call (useActionState) - A <form action=...> with inputs that have a name attribute The mental model shift: Forms used to be controlled state machines you wired up by hand. Now they're a function (the Action) plus a state container (useActionState). Bonus: tag the same Action with "use server" and it runs on the server. The form keeps working without client-side JS. What's the most boilerplate-heavy form you've shipped? Curious how much React 19 would shrink it. #React #React19 #Frontend #WebDev #JavaScript #LearnInPublic
To view or add a comment, sign in
-
-
Most React devs know when to use useLayoutEffect. Almost none can explain why it behaves differently. The answer lives inside the commit phase. React's update cycle has two big stages: render (reconcile, diff, no DOM writes) and commit (apply changes, run effects). Commit itself splits into 3 sub-phases: → Before Mutation — read DOM snapshots before anything changes → Mutation — insert, update, remove DOM nodes → Layout — refs attached, useLayoutEffect fires here, synchronously useEffect never runs in the Layout pass. During reconciliation, React builds an Effect List — fiber nodes tagged with pending work. Fibers marked HookLayout flush during the Layout sub-phase. Fibers marked HookPassive get handed to the scheduler and run after the browser paints. React docs put it directly: "React guarantees that the code inside useLayoutEffect and any state updates scheduled inside it will be processed before the browser repaints the screen." Classic case where this matters: tooltip positioning. With useEffect, users catch a flicker — the tooltip renders in the wrong spot, then jumps. With useLayoutEffect, both renders complete before any pixel changes on screen. The tradeoff: useLayoutEffect blocks paint. Use it only when you need to measure or mutate the DOM before the user sees the frame. Data fetching, subscriptions, analytics — those belong in useEffect. One gotcha: useLayoutEffect is a no-op in SSR. React will warn you. Guard with typeof window !== 'undefined' or default to useEffect in universal code. #frontend #reactjs #javascript #typescript #frontenddevelopment #softwareengineering #webdevelopment
To view or add a comment, sign in
-
-
SSR vs RSC Think of online shopping: **SSR 🛒** You open a product page and get the fully prepared page from the server—but your browser still loads a lot of JavaScript to make it interactive. **RSC 📦** Only the necessary parts are sent to your browser, while heavy work stays on the server—making everything faster and lighter. 👉 SSR = full page, more JS 👉 RSC = less JS, smarter delivery #React #WebDevelopment #Frontend #JavaScript #NextJS #SoftwareEngineering #Programming #WebPerformance #TechExplained
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