Loading

Quipoin Menu

Learn • Practice • Grow

react / Component Lifecycle in React
tutorial

Component Lifecycle in React

Imagine a human life: you are born (birth), you live through different stages (childhood, adulthood), and eventually you pass away. React components have a similar journey – they are created (mounted), they update when something changes, and finally they are removed (unmounted). This journey is called the **component lifecycle**.

What is Component Lifecycle?

Every React component goes through three main phases during its existence:

  1. Mounting: When the component is first created and inserted into the DOM.
  2. Updating: When the component's state or props change, causing it to re-render.
  3. Unmounting: When the component is removed from the DOM.

In class components, we have special methods called lifecycle methods that run at these different phases. In functional components, we use the `useEffect` hook to achieve similar results.

The Three Phases in Detail

1. Mounting Phase
This is when the component is born. It happens when:
  • The app first loads
  • A parent component renders this component for the first time
During mounting, React performs these steps:
  1. Constructor runs (in class components)
  2. render() method is called to create the initial UI
  3. React updates the DOM
  4. componentDidMount() runs (in class components) OR useEffect with empty dependency array runs (in functional components)

2. Updating Phase
This happens when the component's state or props change. The component needs to re-render to reflect the new data.
During updating:
  1. render() is called again
  2. React updates the DOM with the changes
  3. componentDidUpdate() runs (in class components) OR useEffect with dependencies runs (in functional components)

3. Unmounting Phase
This happens when the component is removed from the DOM. This is the cleanup phase.
During unmounting:
  • componentWillUnmount() runs (in class components) OR cleanup function from useEffect runs (in functional components)
  • The component is removed from the DOM

Lifecycle Methods in Class Components

MethodPhasePurpose
constructor()MountingInitialize state, bind methods
render()Mounting/UpdatingReturns JSX to be rendered
componentDidMount()MountingAPI calls, subscriptions, DOM manipulations
componentDidUpdate()UpdatingReact to prop/state changes
componentWillUnmount()UnmountingCleanup (timers, subscriptions)

Example: Class Component with Lifecycle
class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { seconds: 0 };
    console.log('Constructor: Component is being created');
  }

  componentDidMount() {
    console.log('componentDidMount: Component mounted');
    this.interval = setInterval(() => {
      this.setState({ seconds: this.state.seconds + 1 });
    }, 1000);
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('componentDidUpdate: Component updated', prevState, this.state);
  }

  componentWillUnmount() {
    console.log('componentWillUnmount: Component will unmount');
    clearInterval(this.interval);
  }

  render() {
    console.log('render: Rendering UI');
    return <div>Seconds: {this.state.seconds}</div>;
  }
}

Lifecycle in Functional Components (with useEffect)

In modern React with hooks, we don't have separate lifecycle methods. Instead, we use the `useEffect` hook to handle all three phases in a more flexible way.
function Timer() {
  const [seconds, setSeconds] = useState(0);

  <!-- componentDidMount equivalent -->
  useEffect(() => {
    console.log('useEffect: Component mounted');
    const interval = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);

    <!-- componentWillUnmount equivalent -->
    return () => {
      console.log('Cleanup: Component will unmount');
      clearInterval(interval);
    };
  }, []); <!-- Empty dependency array means run once on mount -->

  <!-- componentDidUpdate equivalent (runs when seconds changes) -->
  useEffect(() => {
    console.log('useEffect: seconds updated to', seconds);
  }, [seconds]);

  return <div>Seconds: {seconds}</div>;
}

Two Minute Drill

  • Every React component goes through three phases: Mounting, Updating, and Unmounting.
  • Mounting: Component is created and added to DOM. Good place for API calls and subscriptions.
  • Updating: Component re-renders due to state/prop changes.
  • Unmounting: Component is removed from DOM. Clean up subscriptions, timers, event listeners.
  • Class components have specific lifecycle methods: `componentDidMount`, `componentDidUpdate`, `componentWillUnmount`.
  • Functional components use the `useEffect` hook to handle all lifecycle aspects in a unified way.
  • Understanding lifecycle is crucial for managing side effects and preventing memory leaks.

Need more clarification?

Drop us an email at career@quipoinfotech.com