Skip to main content

Component Lifecycle (Live Playground)

In React, components have a lifecycle that determines when they are created, updated, and destroyed. Understanding the component lifecycle is crucial for managing side effects and optimizing performance. In this tutorial, we'll explore the component lifecycle and its common methods.

Lifecycle Methods

React components have several lifecycle methods that you can use to perform actions at different stages of the component's life. These methods are only available in class components. However, React Hooks provide equivalent functionality for functional components.

Here are the most common lifecycle methods:

  1. componentDidMount: Called after the component is mounted (inserted into the DOM). It is a good place to perform initialization tasks, such as fetching data or subscribing to events.
  2. componentDidUpdate: Called after the component is updated (either due to a change in props or state). It is a good place to perform side effects based on changes or update the DOM.
  3. componentWillUnmount: Called before the component is unmounted (removed from the DOM). It is a good place to perform cleanup tasks, such as canceling network requests or removing event listeners.

Using Lifecycle Methods

To use lifecycle methods in a class component, you need to define the corresponding methods in your component class. Here's an example:

JavaScript
import React from 'react';

class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
seconds: 0,
};
}

componentDidMount() {
this.interval = setInterval(() => {
this.setState({ seconds: this.state.seconds + 1 });
}, 1000);
}

componentDidUpdate(prevProps, prevState) {
if (prevState.seconds % 10 === 0) {
console.log('A multiple of 10 seconds has passed!');
}
}

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

render() {
return <div>Seconds passed: {this.state.seconds}</div>;
}
}

export default Timer;

In this example, we created a Timer component that counts the seconds passed since it was mounted. We used the componentDidMount method to start the timer, the componentDidUpdate method to log a message every 10 seconds, and the componentWillUnmount method to clear the timer when the component is unmounted.

Live Playground, Try it Yourself

Conclusion

Understanding the component lifecycle is essential for managing side effects, optimizing performance, and ensuring proper cleanup in your React applications. Although lifecycle methods are only available in class components, React Hooks provide equivalent functionality for functional components, making it easier to manage component lifecycles in modern React projects.