Performing Cleanup in Class Components:
❓ How:
- Use
componentWillUnmount():- In class components, cleanup tasks such as cancelling network requests, unsubscribing from event listeners, or releasing resources should be performed in the
componentWillUnmount()lifecycle method. This method is invoked immediately before a component is unmounted and destroyed.
- In class components, cleanup tasks such as cancelling network requests, unsubscribing from event listeners, or releasing resources should be performed in the
Code snippet:
class MyComponent extends React.Component { componentDidMount() { // Start network request this.networkRequest = fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); } componentWillUnmount() {// Cancel network request
this.networkRequest.abort();
}
render() {
return <div>My Component</div>;
}
}
In this example
componentDidMount() starts a network request, and componentWillUnmount() cancels the request to avoid memory leaks or unexpected behavior when the component unmounts.
Good Practices:
- Encapsulate Cleanup: Keep cleanup logic within
componentWillUnmount()to ensure consistent and reliable cleanup. - Resource Management: Utilize
componentWillUnmount()for releasing resources to prevent memory leaks and improve performance.
Pitfalls to Avoid:
- Forgetting Cleanup: Missing cleanup tasks can lead to memory leaks or unexpected behavior.
- Incomplete Cleanup: Ensure thorough cleanup to prevent lingering effects that may impact performance or stability.
Note:
Consider using the useEffect() hook's cleanup mechanism for functional components instead of componentWillUnmount().