React JS Tutorial: componentWillUnmount 🎯

beginner
6 min

React JS Tutorial: componentWillUnmount 🎯

Introduction 📝

Hello, friend! Today, we're diving into one of React JS's life-cycle methods: componentWillUnmount. This method helps us clean up resources and prevent memory leaks in our React components. Let's get started!

What is componentWillUnmount? 💡

componentWillUnmount is a method that gets called right before a component is removed from the DOM. This gives us a chance to perform some cleanup tasks before our component is destroyed.

Why use componentWillUnmount? 📝

  1. Prevent Memory Leaks: If our component has subscriptions, timers, or any other resources that consume memory, we should clean them up in componentWillUnmount to prevent memory leaks.
  2. Optimize Performance: By cleaning up resources, we can improve the overall performance of our application.

How to use componentWillUnmount? 💡

  1. Define the method: In your class component, define the componentWillUnmount method:
jsx
class MyComponent extends React.Component { componentWillUnmount() { // Cleanup logic here } // ... Other methods ... }
  1. Perform cleanup: In the method, perform the cleanup tasks. Here's an example where we cancel a setInterval:
jsx
class MyComponent extends React.Component { componentDidMount() { this.intervalId = setInterval(() => { console.log('Hello, world!'); }, 1000); } componentWillUnmount() { clearInterval(this.intervalId); } render() { return <div>My Component</div>; } }

Real-world example 💡

Let's say we have a component that fetches data from an API and updates the state whenever the data changes. However, if the component is unmounted before the data is fetched, we'll get an error since the API request is still running. To prevent this, we can use componentWillUnmount to cancel the API request:

jsx
class MyComponent extends React.Component { state = { data: null }; componentDidMount() { const fetchData = async () => { const response = await fetch('https://api.example.com/data'); const data = await response.json(); this.setState({ data }); }; fetchData(); } componentWillUnmount() { // Cancel the API request this.fetchData.cancel(); } render() { return <div>{this.state.data || 'Loading...'}</div>; } }

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `componentWillUnmount` method do?

Conclusion ✅

Today, we learned about the componentWillUnmount method in React JS. We discussed why it's important to use this method for preventing memory leaks and optimizing performance. We also looked at a real-world example of using componentWillUnmount to cancel API requests. Keep practicing, and happy coding! 🎉