What Are Lifecycle Methods In React? Complete Guide Example

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 state
  • static getDerivedStateFromProps() → sync props to state
  • render() → returns JSX
  • componentDidMount() → runs after the component is rendered

2. Updating

Triggered when props or state changes. Methods:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate() → optimize performance
  • render()
  • getSnapshotBeforeUpdate() → captures DOM info
  • componentDidUpdate() → 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

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *