From componentDidMount to useEffect
You'll learn how to replace class component mount logic with the modern Hook equivalent.
The Class Way: componentDidMount
In class components, when you needed side effects to run once after the component first appeared on screen, you wrote:
class UserProfile extends React.Component {
componentDidMount() {
fetchUserData(this.props.userId);
document.title = `Profile: ${this.props.userName}`;
}
render() {
return <div>...</div>;
}
}
This lifecycle method runs after the first render, perfect for data fetching, subscriptions, or DOM manipulation.
The Hook Way: useEffect with Empty Array
The functional equivalent uses useEffect with an empty dependency array:
function UserProfile({ userId, userName }) {
useEffect(() => {
fetchUserData(userId);
document.title = `Profile: ${userName}`;
}, []); // ← Empty array = run once on mount only
return <div>...</div>;
}
The empty array [] tells React: "This effect has no dependencies, so run it once after mount and never again." It's the componentDidMount translation.
Why the Empty Array Matters
Without the array, the effect runs after every render. With variables in the array, it runs when those change. With an empty array, there's nothing to change—so it runs exactly once, mimicking componentDidMount behavior.
Analogy: It's like setting a one-time alarm. An empty dependency list means "trigger this once when the component wakes up, then forget about it."
Key Takeaway: Replace componentDidMount with useEffect(() => { /* side effect */ }, []) to run setup logic once after the component mounts—the empty dependency array is the critical signal that makes it mount-only.