Q44: How do memory leaks occur in React functional components and how do you prevent them?
Memory leaks happen when asynchronous tasks (API fetches, event listeners, subscriptions, timers) complete after a component unmounts and attempt to update unmounted state. Prevent them using cleanup functions in useEffect or AbortController.
Key Takeaways
- Uncleaned event listeners or pending promises mutating unmounted state cause memory leaks.
- Clean up subscriptions and abort HTTP fetch requests inside effect return callbacks.
Knowledge Check
What is the correct way to cancel an active fetch request inside useEffect on unmount?