React › Class Components & Legacy Lifecycle Methods
What does componentDidMount do in a class component and what is its equivalent using hooks?
IntermediateAnswer
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.