Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to React
React Component Lifecycle Explained

React Component Lifecycle Explained

React1,671 viewsBy Admin
reactcomponentlifecycle

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 methodHook equivalent
componentDidMountuseEffect(fn, [])
componentDidUpdateuseEffect(fn, [deps])
componentWillUnmountreturn 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.