Component Lifecycle

Subject: React

🔍 What is a Component Lifecycle in React?

A lifecycle refers to the stages a component goes through during its existence:

  • Mounting — component is created and inserted into the DOM.
  • Updating — component updates due to changes in props or state.
  • Unmounting — component is removed from the DOM.

Each phase has specific lifecycle methods (Class) or React Hooks (Function).


🏗️ 1. Mounting Phase

🔹 Class Component Methods

Class MethodPurpose
constructor()Initialize state and bind methods
render()Return JSX (required)
componentDidMount()Runs once after component is inserted

🔹 Hook Equivalent

HookPurpose
useStateSame as constructor state setup
useEffect(..., [])Runs once after first render

🔄 2. Updating Phase

🔹 Class Component Methods

MethodWhen It Runs
componentDidUpdate()After re-render (on state/prop change)
shouldComponentUpdate()Decide whether re-render should happen

🔹 Hook Equivalent

HookPurpose
useEffect(..., [dep])Runs when dependency (dep) changes
React.memo + useCallbackFor performance optimization (like SCU)

🗑️ 3. Unmounting Phase

🔹 Class Component Method

🔹 Hook Equivalent


🧠 Summary Table: Class vs Hook Lifecycle

Lifecycle StageClass ComponentFunctional Component (Hooks)
Initialize Stateconstructor()useState()
On MountcomponentDidMount()useEffect(() => {}, [])
On UpdatecomponentDidUpdate()useEffect(() => {}, [deps])
On UnmountcomponentWillUnmount()useEffect(() => return => {}, [])
Control UpdatesshouldComponentUpdate()React.memo, useCallback

🔍 Extra Notes

  • render() is only in class components. In functional components, the return statement acts as render.
  • Hooks allow more granular and reusable side effect handling.
  • Rules of Hooks: Must be called at the top level and only in React functions.