Cleaning Up Resources
This example demonstrates the significance of managing resources and cleaning up events in React components.
When working with event listeners like resize, it's crucial to remove them when the component unmounts to prevent memory leaks and unexpected behavior.
The useEffect hook is used to add the event listener on component mount and to return a cleanup function that removes it on unmount.
In React, it's essential to clean up not only event listeners but also other resources like timers, WebSocket connections, data subscriptions, and interactions with third-party libraries to ensure efficient memory management and avoid performance issues. This practice helps maintain the stability and predictability of your application.
import { useEffect, useState } from "react";
const Nine = () => {
// Not using custom hooks
const [windowSize, setWindowSize] = useState(1920);
useEffect(() => {
const handleWindowSizeChange = () => {
setWindowSize(window.innerHeight);
};
window.addEventListener("resize", handleWindowSizeChange);
// Return a cleanup function
return () => {
window.removeEventListener("resize", handleWindowSizeChange);
}; // cleanup is necessary for this event - events always need to be cleaned up
}, []);
return <div>Component1</div>;
};
export default Nine;
/*
In React, especially when working with hooks, it's important to properly manage
the component's lifecycle and clean up resources to avoid memory leaks and other
potential issues. Let's consider why it's important to clean up events and what else
needs to be cleaned up in components.
Why should events always be cleaned up?
Memory leaks: If you don't remove event listeners, they remain in memory even after
the component is unmounted, which can lead to memory leaks.
Unexpected behavior: Event listeners left after a component is unmounted may continue
to fire, causing code to execute at inappropriate times, leading to errors and unpredictable behavior.
Performance: Unnecessary event listeners can degrade application performance, especially
if they are triggered frequently (e.g., on window resize or scroll).
What else should be cleaned up?
Timers and intervals: If you use setTimeout or setInterval, they need to be
cleared using clearTimeout and clearInterval.
WebSockets and connections: If your component establishes a connection through
a WebSocket or another type of connection, the connection should be closed when the component is unmounted.
Subscriptions to data streams (e.g., Observables): If your component subscribes
to a data stream (e.g., using the RxJS library), you should unsubscribe when the component is unmounted.
Third-party libraries: If your component interacts with third-party libraries
that have their own cleanup methods, these methods should be called when the component is unmounted.
*/