Course contentsShow
← React
Lesson 305 of 2,3969. Class Components (Legacy Overview)Free lesson

Common Lifecycle Patterns: Fetch on Mount

The standard pattern of fetching data in componentDidMount and cleaning up in componentWillUnmount.

Common Lifecycle Patterns: Fetch on Mount

You'll learn the most common real-world use of class component lifecycles: fetching data when your component first appears and cleaning up when it disappears.

The Standard Pattern

In almost every legacy codebase, you'll see this pattern repeated: fetch data in componentDidMount and clean up in componentWillUnmount. This is the bread-and-butter of data loading in class components.

Why this pattern exists:

When your component first renders, it often needs external data (from an API, database, etc.). You can't fetch during render() itself—that method must be pure. Instead, you wait until the component mounts (appears in the DOM), then trigger your side effect in componentDidMount.

The Basic Structure

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

  componentDidMount() {
    // Start fetching data after first render
    fetch(`/api/users/${this.props.userId}`)
      .then(response => response.json())
      .then(user => {
        this.setState({ user, loading: false });
      });
  }

  componentWillUnmount() {
    // Optional: cancel requests or clean up subscriptions
    // (prevents setting state on unmounted components)
  }

  render() {
    if (this.state.loading) return <div>Loading...</div>;
    return <div>{this.state.user.name}</div>;
  }
}

Think of it like a restaurant order: when you sit down (mount), you place your order (fetch). While you wait, you show a "preparing your meal" message (loading state). When your food arrives (data returns), you display it. When you leave (unmount), you cancel any pending orders.

Key Takeaway: The fetch-on-mount pattern uses componentDidMount to start data loading after the first render and componentWillUnmount to clean up, preventing memory leaks from setting state on unmounted components.