Lifecycle methods are special functions in React class components that run at specific stages of a component’s life.
They allow developers to control behavior during mounting, updating, and unmounting.
Lifecycle Phases
1. Mounting
Occurs when a component is created and inserted into the DOM. Common methods:
constructor()→ initialize statestatic getDerivedStateFromProps()→ sync props to staterender()→ returns JSXcomponentDidMount()→ runs after the component is rendered
2. Updating
Triggered when props or state changes. Methods:
static getDerivedStateFromProps()shouldComponentUpdate()→ optimize performancerender()getSnapshotBeforeUpdate()→ captures DOM infocomponentDidUpdate()→ runs after update
3. Unmounting
Occurs when a component is removed from the DOM.
componentWillUnmount()→ cleanup tasks like timers, subscriptions
Example of Lifecycle Methods
class Timer extends React.Component {
constructor() {
super();
this.state = { seconds: 0 };
}
componentDidMount() {
this.interval = setInterval(() => {
this.setState({ seconds: this.state.seconds + 1 });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <h2>Seconds: {this.state.seconds}</h2>;
}
}
Conclusion
Lifecycle methods give control over how components behave during creation, updates, and removal. They are essential for class-based React apps.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP