Fix debounce memory leak#488
Conversation
✅ Deploy Preview for github-spy ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
Warning Review limit reached
Your plan currently allows 1 review/hour. Refill in 28 minutes and 19 seconds. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more review capacity refills, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than trial, open-source, and free plans. In all cases, review capacity refills continuously over time. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
🎉🎉 Thank you for your contribution! Your PR #488 has been merged! 🎉🎉 |
Related Issue
Description
🧱 The Architectural Context:
React components execute updates dynamically based on continuous state adjustments. If an asynchronous micro-task (like a network fetch or a
setTimeoutclock) finishes processing after its parent component has already unmounted from the DOM, triggering a state setter function causes a severe memory leak warning in the browser console.❌ The Failure Mechanism:
The original
useDebouncehook initialized asetTimeoutscheduler every time a character was typed into a search input. If a user typed a character and immediately clicked a navigation link to change pages before the delay timer finished, the component tree unmounted, but the background browser timer remained active in the event loop. Once the timer completed, it attempted to callsetDebouncedValue(value).💥 The Impact:
This triggered the classic React runtime warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak. In larger applications, thousands of these uncleaned micro-tasks degrade client-side performance, exhaust system memory, and cause sluggish UI responses.
✅ The Solution:
Integrated a persistent tracking reference pointer using
useRef(true)alongside an explicit cleanup routine. This ensures that the component safely clears any remaining background timer threads viaclearTimeoutand flags the tracking node asfalsethe exact millisecond the component unmounts, preventing unmounted state state adjustments entirely.Type of Change