Conteúdo do curso
React.js: Understand and Apply the Lifecycle
Sobre a Aula

Class 04 — Component disassembly (componentWillUnmount)

componentWillUnmount is a lifecycle method in React class components. It is called when a component is about to be removed from the DOM tree.

Why is componentWillUnmount Important?

This method is useful for cleaning up resources and preventing memory leaks. For example, you can clear timers, cancel event subscriptions, or uninstall listeners.

How to use componentWillUnmount

Define it as a method inside a React class. For example:

class MyComponent extends React.Component {
  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    console.log('The timer is working.');
  }

  render() {
    return <div>My Component</div>;
  }
}

In this example, the componentDidMount method sets a timer when the component is mounted. The componentWillUnmount method clears that timer when the component is unmounted. This prevents the timer from running after the component is removed.

Cleanup Examples

Besides clearing timers, you can use componentWillUnmount to:

  1. Cancel network requests: componentWillUnmount() { this.abortController.abort(); }
  2. Unregister global events: componentDidMount() { window.addEventListener('resize', this.handleResize); } componentWillUnmount() { window.removeEventListener('resize', this.handleResize); }
  3. Clear service subscriptions: componentDidMount() { this.subscription = someService.subscribe(data => this.setState({ data })); } componentWillUnmount() { this.subscription.unsubscribe(); }

Conclusion

componentWillUnmount is crucial for ensuring that your component cleans up resources when it is no longer needed.

This keeps your React application efficient and prevents performance issues. Practice implementing it in your components to see how it works in practice.

Entrar na conversa
Rolar para cima