In which lifeCycle method should you perform cleanup taks (like cancelling network requests) for class components?

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.

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:

  1. Encapsulate Cleanup: Keep cleanup logic within componentWillUnmount() to ensure consistent and reliable cleanup.
  2. Resource Management: Utilize componentWillUnmount() for releasing resources to prevent memory leaks and improve performance.

Pitfalls to Avoid:

  1. Forgetting Cleanup: Missing cleanup tasks can lead to memory leaks or unexpected behavior.
  2. 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().