React lifecycle refers to the different phases a component goes through from creation to removal from the DOM.
A component’s life has three main phases:
- Mounting
- Updating
- Unmounting
🔵 1. Lifecycle Methods (Class Components)
✅ Mounting Phase
(Component is created and added to DOM)
| Method | Purpose |
|---|---|
constructor() |
Initialize state, bind methods |
static getDerivedStateFromProps() |
Sync state with props |
render() |
Return JSX |
componentDidMount() |
API calls, subscriptions |
componentDidMount() {
fetchData();
}
✅ Updating Phase
(Component re-renders due to state/prop changes)
| Method | Purpose |
|---|---|
shouldComponentUpdate() |
Performance optimization |
render() |
Re-render UI |
componentDidUpdate() |
React to updates |
componentDidUpdate(prevProps, prevState) {
if (prevProps.id !== this.props.id) {
fetchData();
}
}
✅ Unmounting Phase
(Component removed from DOM)
| Method | Purpose |
|---|---|
componentWillUnmount() |
Cleanup |
componentWillUnmount() {
clearInterval(timer);
}
🔥 2. Lifecycle Hooks (Functional Components)
Hooks replace lifecycle methods in functional components.
✅ useEffect — All Lifecycle in One Hook
| Lifecycle Phase | Hook Usage |
|---|---|
| Mount | useEffect(() => {}, []) |
| Update | useEffect(() => {}, [deps]) |
| Unmount | useEffect(() => { return () => {} }, []) |
🧪 Example:
useEffect(() => {
console.log("Mounted");
return () => {
console.log("Unmounted");
};
}, []);
✅ useLayoutEffect
Like useEffect, but runs before browser paint.
Used for:
- DOM measurements
- Layout calculations
🧠 Lifecycle Mapping (Class → Hooks)
| Class Method | Hook Equivalent |
|---|---|
componentDidMount |
useEffect(() => {}, []) |
componentDidUpdate |
useEffect(() => {}, [deps]) |
componentWillUnmount |
Cleanup in useEffect |
shouldComponentUpdate |
React.memo, useMemo |
🎯 Short Interview Answer
React lifecycle methods define the stages of a component’s life: mounting, updating, and unmounting.
In class components, lifecycle methods likecomponentDidMount,componentDidUpdate, andcomponentWillUnmountmanage these stages.
In functional components, Hooks likeuseEffectanduseLayoutEffecthandle lifecycle behavior.
⭐ One-Line Summary
Lifecycle methods/hooks control what happens when a React component mounts, updates, and unmounts.