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!
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.
componentWillUnmount? 📝componentWillUnmount to prevent memory leaks.componentWillUnmount? 💡componentWillUnmount method:class MyComponent extends React.Component {
componentWillUnmount() {
// Cleanup logic here
}
// ... Other methods ...
}class MyComponent extends React.Component {
componentDidMount() {
this.intervalId = setInterval(() => {
console.log('Hello, world!');
}, 1000);
}
componentWillUnmount() {
clearInterval(this.intervalId);
}
render() {
return <div>My Component</div>;
}
}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:
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>;
}
}What does the `componentWillUnmount` method do?
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! 🎉