React Component Lifecycle Explained
Ad
The Three Lifecycle Phases
Every React component goes through three phases: Mounting (added to DOM), Updating (re-rendered), and Unmounting (removed). With hooks, all three are handled by useEffect.
Mounting — Component is Born
useEffect(() => {
console.log("Component mounted");
// fetch data, set up subscriptions
}, []); // empty deps = runs once on mount
Updating — State or Props Change
useEffect(() => {
console.log("count changed to", count);
}, [count]); // runs whenever count updates
Unmounting — Component is Removed
useEffect(() => {
const sub = subscribe();
return () => {
sub.unsubscribe(); // cleanup runs on unmount
console.log("Component unmounted");
};
}, []);
Class Lifecycle Methods (Legacy)
| Class method | Hook equivalent |
|---|---|
| componentDidMount | useEffect(fn, []) |
| componentDidUpdate | useEffect(fn, [deps]) |
| componentWillUnmount | return cleanup in useEffect |
FAQs
Should I learn class lifecycle methods?
Only to maintain old code. New React is written with function components and hooks.
What order do effects run in?
Top to bottom, after the DOM updates. Cleanups run before the next effect and on unmount. More in our React section.
