Component Lifecycle Methods in React
What is Component Lifecycle?
Component lifecycle in React is a sequence of stages that component goes through from its creation to removal from DOM.
Lifecycle exists only for class components, but its behavior can be replicated using hooks in functional components.
Lifecycle Stages
Lifecycle is divided into 3 key phases:
| Phase | Description |
|---|---|
| Mounting | Moment component appears in DOM |
| Updating | Component update when changes occur |
| Unmounting | Component removal from DOM |
Mounting Phase Methods
| Method | When called |
|---|---|
constructor | At component creation moment |
static getDerivedStateFromProps | Before render (rarely used) |
render | Required method, returns JSX |
componentDidMount | After mounting to DOM |
Updating Phase Methods
| Method | When called |
|---|---|
static getDerivedStateFromProps | When props update |
shouldComponentUpdate | Before re-render (can cancel it) |
render | At every update |
getSnapshotBeforeUpdate | DOM snapshot before update |
componentDidUpdate | After component update |
Unmounting Phase Method
| Method | When called |
|---|---|
componentWillUnmount | Before component removal from DOM |
Functional Component Equivalents
Hook functions allow replicating lifecycle behavior:
| Class method | Hook in function |
|---|---|
componentDidMount | useEffect(() => {}, []) |
componentDidUpdate | useEffect(() => {...}, [dep]) |
componentWillUnmount | useEffect(() => { return () => {...} }, []) |
shouldComponentUpdate | React.memo() + useCallback, useMemo |
Hook Usage Example
import { useEffect } from "react";
function MyComponent() {
useEffect(() => {
console.log("Component mounting");
return () => {
console.log("Component unmounting");
};
}, []);
return <div>Hello!</div>;
}
Tip:
In new projects it's better to use functional components with hooks — they're simpler, more concise and recommended by React community.