Skillversitas

Component Lifecycle

What Is a Component Lifecycle?

Every React component goes through a series of stages from the moment it is created until it is destroyed. This life cycle is known as the component lifecycle. Understanding the lifecycle helps us manage side effects such as data fetching, subscriptions, and resource cleanup.

The Three Main Stages

Stage Description
Mounting The component is created and inserted into the DOM
Updating Props or state change, causing a re-render
Unmounting The component is removed from the DOM

Lifecycle in Class Components

Class components provide special methods for each stage.

Mounting Methods

class UserProfile extends React.Component {
  constructor(props) {
    super(props);
    this.state = { user: null };
  }

  componentDidMount() {
    // Called after the component is inserted into the DOM
    fetch(`/api/users/${this.props.userId}`)
      .then(res => res.json())
      .then(user => this.setState({ user }));
  }

  render() {
    if (!this.state.user) return <p>Loading...</p>;
    return <h2>{this.state.user.name}</h2>;
  }
}

Updating Methods

componentDidUpdate(prevProps, prevState) {
  // Called after an update
  if (prevProps.userId !== this.props.userId) {
    fetch(`/api/users/${this.props.userId}`)
      .then(res => res.json())
      .then(user => this.setState({ user }));
  }
}

Unmounting Methods

componentWillUnmount() {
  // Clean up resources before the component is removed
  clearInterval(this.timer);
  this.subscription.unsubscribe();
}

Lifecycle with Hooks

React Hooks replace lifecycle methods in function components.

Class Method Hook Equivalent
componentDidMount useEffect(() => {}, [])
componentDidUpdate useEffect(() => {}, [deps])
componentWillUnmount Return a function from useEffect
function UserProfile({ userId }) {
  const [user, setUser] = React.useState(null);

  React.useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then(setUser);

    return () => {
      // Cleanup like componentWillUnmount
    };
  }, [userId]); // Dependency array like componentDidUpdate

  if (!user) return <p>Loading...</p>;
  return <h2>{user.name}</h2>;
}

Hooks simplify the lifecycle by combining several methods into a single useEffect. In the next chapter, we will study hooks in depth, starting with an introduction to hooks.