Advertisement
Intermediate React, Class Components & Legacy Lifecycle Methods

What does componentDidMount do in a class component and what is its equivalent using hooks?

Short answer

componentDidMount runs one time, right after a component first appears on the screen. It is commonly used to fetch data from a server or set up something like a timer.

Save React mock interview
Advertisement
AModel answer
componentDidMount runs one time, right after a component first appears on the screen. It is commonly used to fetch data from a server or set up something like a timer. Using hooks, the same behavior is achieved with useEffect and an empty dependency array, which tells React to only run it once.
// Class component
componentDidMount() {
  fetchUserData(this.props.userId).then((data) => this.setState({ user: data }));
}

// Function component with a hook
useEffect(() => {
  fetchUserData(userId).then((data) => setUser(data));
}, []);
Real-world example
An older dashboard component uses componentDidMount to load a user's profile information as soon as the page opens, exactly the same behavior a modern component would achieve with useEffect and an empty array.
Likely follow-ups
  • What happens if you forget to pass an empty array to useEffect when trying to copy componentDidMount behavior?
  • What class method is used to clean something up when a component is removed from the screen?
Related topics