In React, lifecycle events (or lifecycle methods) refer to the specific points in a component's life where you can execute code in response to changes or actions. These events help you manage tasks such as data fetching, subscriptions, and cleaning up resources.
In class components, lifecycle methods are divided into three main phases:
constructor()
: Called when the component is initialized.componentDidMount()
: Called immediately after the component is mounted. Ideal for data fetching.componentDidUpdate(prevProps, prevState)
: Called after the component has updated. Good for operations based on prop/state changes.componentWillUnmount()
: Ideal for cleanup tasks, like invalidating timers or canceling network requests.class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component updated');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Component mounted or count updated');
}, [count]); // Runs on mount and when count changes
useEffect(() => {
console.log('Component mounted');
return () => {
console.log('Component will unmount');
};
}, [])
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}