Blog>
Snippets

Lifecycle Methods Usage

Explain and exemplify how to use React lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components.
class MyComponent extends React.Component {
  // Constructor for initializing state and binding methods
  constructor(props) {
    super(props);
    this.state = { hasMounted: false };
  }

  // Called after the component is mounted to the DOM.
  componentDidMount() {
    this.setState({ hasMounted: true });
    // You can also perform AJAX requests or DOM operations here
  }

  // Called after the component updates due to state or prop changes.
  componentDidUpdate(prevProps, prevState) {
    if (this.props.userID !== prevProps.userID) {
      // Fetch new data using this.props.userID
    }
  }

  // Called right before the component is unmounted and destroyed.
  componentWillUnmount() {
    // Perform any necessary cleanup, such as invalidating timers,
    // canceling network requests, or cleaning up any subscriptions
  }

  render() {
    return (
      <div>{`The component has ${this.state.hasMounted ? '' : 'not '}mounted.`}</div>
    );
  }
}
This example showcases how to use the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods. componentDidMount is used to change the state once the component is mounted, which could also be the place for API calls. componentDidUpdate compares current props with previous ones and fetches new data if they have changed. componentWillUnmount is used for cleanup to avoid memory leaks.