"If components were humans, their lifecycle would be: born, grow, and say goodbye."
Hello dear coders!
In this cheerful guide, we’ll explore the lifecycle of React components. We’ll compare the classic Class Components with their lifecycle methods and the modern Function Components using useEffect
.
What Is a Lifecycle?
React components have a life — they mount, update, and unmount. Each phase gives you hooks to run code at just the right time.
3 Phases of Lifecycle:
- Mounting – Component appears in the DOM
- Updating – Props or state changes
- Unmounting – Component removed from DOM
Lifecycle in Class Components
class MyComponent extends React.Component {
componentDidMount() {
console.log("Mounted");
}
componentDidUpdate(prevProps, prevState) {
console.log("Updated");
}
componentWillUnmount() {
console.log("Unmounting");
}
render() {
return <div>Hello Class Component</div>;
}
}
componentDidMount
Runs once after the component is rendered. Great for fetching data!
componentDidUpdate
Runs after props/state changes. Compare with previous values to conditionally run logic.
componentWillUnmount
Clean up timers, listeners, etc. Just before the component disappears.
useEffect: Lifecycle in Function Components
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
console.log("Mounted");
return () => {
console.log("Unmounting");
};
}, []);
return <div>Hello useEffect</div>;
}
Mount Only
useEffect(() => {
console.log("Component mounted");
}, []);
Every Render
useEffect(() => {
console.log("Component updated or mounted");
});
Unmount Cleanup
useEffect(() => {
const timer = setInterval(() => console.log("tick"), 1000);
return () => clearInterval(timer);
}, []);
Comparison Table
Lifecycle Phase | Class Method | useEffect |
---|---|---|
Mount | componentDidMount | useEffect(..., []) |
Update | componentDidUpdate | useEffect(...) |
Unmount | componentWillUnmount | return () => {} |
Real Example: Timer
Class Component
class Timer extends React.Component {
state = { count: 0 };
componentDidMount() {
this.interval = setInterval(() => {
this.setState(prev => ({ count: prev.count + 1 }));
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <p>{this.state.count}s</p>;
}
}
Function Component
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => setCount(c => c + 1), 1000);
return () => clearInterval(interval);
}, []);
return <p>{count}s</p>;
}
Tips and Gotchas
- Always add dependencies in
useEffect
array - Use multiple
useEffect
instead of nesting logic - Don’t forget cleanup functions!
Advanced: Fetch API in useEffect
useEffect(() => {
fetch(`/api/user/${userId}`)
.then(res => res.json())
.then(data => setUser(data));
}, [userId]);
useLayoutEffect vs useEffect
useLayoutEffect
runs synchronously before painting the screen. Only use if needed for precise layout control.
Whether you're using old-school class components or modern functional components, understanding lifecycle methods helps you build powerful and efficient apps.
"React lifecycles are like concerts — intro, performance, and closing act. The more you understand them, the smoother the show."
0 Comments:
Post a Comment