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 Method | Purpose |
---|---|
constructor() | Initialize state and bind methods |
render() | Return JSX (required) |
componentDidMount() | Runs once after component is inserted |
🔹 Hook Equivalent
Hook | Purpose |
---|---|
useState | Same as constructor state setup |
useEffect(..., []) | Runs once after first render |
🔄 2. Updating Phase
🔹 Class Component Methods
Method | When It Runs |
---|---|
componentDidUpdate() | After re-render (on state/prop change) |
shouldComponentUpdate() | Decide whether re-render should happen |
🔹 Hook Equivalent
Hook | Purpose |
---|---|
useEffect(..., [dep]) | Runs when dependency (dep) changes |
React.memo + useCallback | For performance optimization (like SCU) |
🗑️ 3. Unmounting Phase
🔹 Class Component Method
🔹 Hook Equivalent
🧠 Summary Table: Class vs Hook Lifecycle
Lifecycle Stage | Class Component | Functional Component (Hooks) |
---|---|---|
Initialize State | constructor() | useState() |
On Mount | componentDidMount() | useEffect(() => {}, []) |
On Update | componentDidUpdate() | useEffect(() => {}, [deps]) |
On Unmount | componentWillUnmount() | useEffect(() => return => {}, []) |
Control Updates | shouldComponentUpdate() | 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.
Advertisement Slot 1
Advertisement Slot 2