Hack Frontend Community

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:

PhaseDescription
MountingMoment component appears in DOM
UpdatingComponent update when changes occur
UnmountingComponent removal from DOM

Mounting Phase Methods

MethodWhen called
constructorAt component creation moment
static getDerivedStateFromPropsBefore render (rarely used)
renderRequired method, returns JSX
componentDidMountAfter mounting to DOM

Updating Phase Methods

MethodWhen called
static getDerivedStateFromPropsWhen props update
shouldComponentUpdateBefore re-render (can cancel it)
renderAt every update
getSnapshotBeforeUpdateDOM snapshot before update
componentDidUpdateAfter component update

Unmounting Phase Method

MethodWhen called
componentWillUnmountBefore component removal from DOM

Functional Component Equivalents

Hook functions allow replicating lifecycle behavior:

Class methodHook in function
componentDidMountuseEffect(() => {}, [])
componentDidUpdateuseEffect(() => {...}, [dep])
componentWillUnmountuseEffect(() => { return () => {...} }, [])
shouldComponentUpdateReact.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.