🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEreact

react Documentation

LOADING ENGINE...

ComponentDidMount

AI & DATA SCIENCE // componentdidmount

componentDidMount is a class component lifecycle method that runs once, immediately after the component's initial render has been committed to the DOM.

Syntax

class MyComponent extends React.Component {
  componentDidMount() {
    // runs once, after initial render
  }
}

Deep Dive Course

componentDidMount fires exactly once per component instance, right after that component's first render has been committed to the real DOM — this makes it the traditional class-component place to perform initial side effects like fetching data, setting up a subscription, or reading a DOM node's measurements, since the actual DOM elements are guaranteed to exist by this point, unlike during render() itself. In functional components, the equivalent behavior is achieved with useEffect(() => { ... }, []), an effect with an empty dependency array, which likewise runs exactly once after the initial mount.

1Understanding ComponentDidMount

componentDidMount fires exactly once per component instance, right after that component's first render has been committed to the real DOM — this makes it the traditional class-component place to perform initial side effects like fetching data, setting up a subscription, or reading a DOM node's measurements, since the actual DOM elements are guaranteed to exist by this point, unlike during render() itself. In functional components, the equivalent behavior is achieved with useEffect(() => { ... }, []), an effect with an empty dependency array, which likewise runs exactly once after the initial mount.

💡

componentDidMount's functional-component equivalent is useEffect(() => { ... }, []) — an empty dependency array specifically means the effect runs once, matching componentDidMount's once-per-mount behavior.

editor.html
class UserProfile extends React.Component {
  state = { name: null };
  componentDidMount() {
    console.log('Component mounted, fetching data...');
    fetchUser(this.props.userId).then(user => this.setState({ name: user.name }));
  }
  render() {
    return <p>{this.state.name ?? 'Loading...'}</p>;
  }
}
localhost:3000

2Practical Example

Here is a real-world application of ComponentDidMount showing how it is used in production React code.

editor.html
class ClickTracker extends React.Component {
  componentDidMount() {
    document.addEventListener('click', this.logClick);
  }
  componentWillUnmount() {
    document.removeEventListener('click', this.logClick);
  }
  logClick = () => console.log('Document clicked');
  render() {
    return <p>Tracking clicks...</p>;
  }
}
localhost:3000

3Best Practices

Follow these guidelines when working with ComponentDidMount:

1. Perform initial data fetching, subscriptions, or DOM measurements in componentDidMount, since the component's actual DOM nodes are guaranteed to exist by that point

2. Avoid calling this.setState() synchronously and unconditionally inside componentDidMount without a real reason, since it triggers an extra, avoidable re-render right after the initial one

3. Recognize componentDidMount only appears in class components — write the equivalent useEffect(fn, []) when working in functional components instead

⚠️

Tip: componentDidMount's functional-component equivalent is useEffect(() => { ... }, []) — an empty dependency array specifically means the effect runs once, matching componentDidMount's once-per-mount behavior.

editor.html
class UserProfile extends React.Component {
  state = { name: null };
  componentDidMount() {
    console.log('Component mounted, fetching data...');
    fetchUser(this.props.userId).then(user => this.setState({ name: user.name }));
  }
  render() {
    return <p>{this.state.name ?? 'Loading...'}</p>;
  }
}
localhost:3000

Examples

Example 01Basic Usage
class UserProfile extends React.Component {
  state = { name: null };
  componentDidMount() {
    console.log('Component mounted, fetching data...');
    fetchUser(this.props.userId).then(user => this.setState({ name: user.name }));
  }
  render() {
    return <p>{this.state.name ?? 'Loading...'}</p>;
  }
}
Example 02Advanced Example
class ClickTracker extends React.Component {
  componentDidMount() {
    document.addEventListener('click', this.logClick);
  }
  componentWillUnmount() {
    document.removeEventListener('click', this.logClick);
  }
  logClick = () => console.log('Document clicked');
  render() {
    return <p>Tracking clicks...</p>;
  }
}

Best Practices

  • Perform initial data fetching, subscriptions, or DOM measurements in componentDidMount, since the component's actual DOM nodes are guaranteed to exist by that point
  • Avoid calling this.setState() synchronously and unconditionally inside componentDidMount without a real reason, since it triggers an extra, avoidable re-render right after the initial one
  • Recognize componentDidMount only appears in class components — write the equivalent useEffect(fn, []) when working in functional components instead

Interview Question

Why is componentDidMount, rather than the render() method itself, considered the right place to fetch data or read a DOM node's measurements in a class component?

Hint: Think about whether the actual DOM elements a component describes are guaranteed to exist yet during render() versus after componentDidMount fires.

render() is only responsible for describing what the JSX/virtual DOM should look like, it doesn't guarantee that the actual, real DOM nodes matching that description already exist in the browser at the moment render() itself is executing, since the commit phase, where React actually updates the real DOM, happens afterward. componentDidMount specifically fires only after that commit phase has completed for the component's initial render, which is exactly why it's the reliable point at which the component's actual DOM nodes are guaranteed to exist and be measurable, safe for operations like reading an element's rendered size or attaching an event listener directly to it. Performing that same DOM-dependent work directly inside render() would be unreliable, since render() can be called before the corresponding real DOM nodes exist yet, and render() is also meant to remain a pure, side-effect-free function of props and state, not a place to fetch data or interact with the DOM directly.

Exercises

MediumPractice using ComponentDidMount in a real scenario.
View Solution
class UserProfile extends React.Component {
  state = { name: null };
  componentDidMount() {
    console.log('Component mounted, fetching data...');
    fetchUser(this.props.userId).then(user => this.setState({ name: user.name }));
  }
  render() {
    return <p>{this.state.name ?? 'Loading...'}</p>;
  }
}

Frequently Asked Questions

Why is componentDidMount, rather than the render() method itself, considered the right place to fetch data or read a DOM node's measurements in a class component?

render() is only responsible for describing what the JSX/virtual DOM should look like, it doesn't guarantee that the actual, real DOM nodes matching that description already exist in the browser at the moment render() itself is executing, since the commit phase, where React actually updates the real DOM, happens afterward. componentDidMount specifically fires only after that commit phase has completed for the component's initial render, which is exactly why it's the reliable point at which the component's actual DOM nodes are guaranteed to exist and be measurable, safe for operations like reading an element's rendered size or attaching an event listener directly to it. Performing that same DOM-dependent work directly inside render() would be unreliable, since render() can be called before the corresponding real DOM nodes exist yet, and render() is also meant to remain a pure, side-effect-free function of props and state, not a place to fetch data or interact with the DOM directly.

Related Functions

componentdidupdatecomponentwillunmountuseeffect