The cleanup function in useEffect runs before the component unmounts and before re-running the effect, used to prevent memory leaks.
The useEffect hook can return a cleanup function that React will call when the component unmounts or before the effect runs again. This cleanup mechanism is essential for preventing memory leaks and ensuring proper resource management.
Common use cases for cleanup functions include: clearing timers (setTimeout, setInterval), unsubscribing from event listeners, canceling API requests or subscriptions, closing WebSocket connections, and cleaning up any external resources your effect creates.
For example, if you set up a subscription in useEffect, you should return a function that unsubscribes. If you add an event listener to the window, you should return a function that removes it. This pattern ensures that each effect cleans up after itself.
The cleanup runs in a specific order: when a component unmounts, the cleanup from the last render runs. When an effect re-runs due to dependency changes, the cleanup from the previous effect runs before the new effect executes. This helps prevent stale closures and ensures the previous effect is fully cleaned up before setting up the new one.
The cleanup function in useEffect runs before the component unmounts and before re-running the effect, used to prevent memory leaks.
Join our network of elite AI-native engineers.