React Component Lifecycle — React Technical Interview Questions & Answers
React Component Lifecycle
React Component Lifecycle
- Three big phases: mount (first appear), update (props/state change), unmount (leave the tree). Class names: componentDidMount, componentDidUpdate, componentWillUnmount. Effects map: useEffect(() => { mount/update work; return cleanup; }, deps).
- Empty deps [] ≈ mount + unmount cleanup. [id] ≈ re-run when id changes. Missing deps ≈ run after every paint — easy to create loops if you setState inside.
- Board clock: start interval on mount, clearInterval on unmount. Forget cleanup → ghost timers after you leave the page. That story is the lifecycle viva.
- React Component Lifecycle — on screen: 0s, 1s, 2s… Leave page → cleanup. componentDidMount ≈ useEffect(() => {}, []).
render
│
▼
useEffect
│ unmount
▼
cleanup()Technical Interview Tip: Map didMount to useEffect([]). Mention cleanup.
Code Examples for React Component Lifecycle
Example
// Lifecycle ≈ useEffect
import { useEffect, useState } from "react";
export default function Clock() {
const [t, setT] = useState(0);
useEffect(() => {
const id = setInterval(() => setT((x) => x + 1), 1000);
return () => clearInterval(id);
}, []);
return <p>{t}s</p>;
}
React Component Lifecycle — on screen: 0s, 1s, 2s… Leave page → cleanup. componentDidMount ≈ useEffect(() => {}, []).
How to Explain React Component Lifecycle to an Interviewer
What is componentDidMount in hooks?
useEffect(() => {}, [])
Why return a function from useEffect?
Cleanup Timers / subscriptions