Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
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 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 |
| Method | When called |
|---|---|
constructor | At component creation moment |
static getDerivedStateFromProps | Before render (rarely used) |
render | Required method, returns JSX |
componentDidMount | After mounting to DOM |
| 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 |
| Method | When called |
|---|---|
componentWillUnmount | Before component removal from DOM |
Hook functions allow replicating lifecycle behavior:
| Class method | Hook in function |
|---|---|
componentDidMount | useEffect(() => {}, []) |
componentDidUpdate | useEffect(() => {...}, [dep]) |
componentWillUnmount | useEffect(() => { return () => {...} }, []) |
shouldComponentUpdate | React.memo() + useCallback, useMemo |
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.