#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Class Based Components

Component Life Cycle and in Action

The component life cycle is the series of stages a React class component goes through: it is created and added to the page (mounting), it re-renders when props or state change (updating), and it is removed (unmounting). Class components expose special methods for each stage, so you can run code at exactly the right moment, such as fetching data after the first render or clearing a timer before the component disappears.

The three phases and their methods

PhaseCommon methods, in order
Mountingconstructor, render, componentDidMount
UpdatingshouldComponentUpdate, render, componentDidUpdate
UnmountingcomponentWillUnmount

There are a few rarer ones, such as getDerivedStateFromProps and getSnapshotBeforeUpdate, but the methods above cover most real code.

Seeing the life cycle in action

This clock component uses all three phases. It sets up initial state in the constructor, starts a timer once it is on the page, reacts to a prop change, and cleans up when it leaves.

import React from 'react';

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { now: new Date() };
  }

  componentDidMount() {
    this.timerId = setInterval(() => {
      this.setState({ now: new Date() });
    }, 1000);
  }

  componentDidUpdate(prevProps) {
    if (prevProps.label !== this.props.label) {
      document.title = this.props.label;
    }
  }

  componentWillUnmount() {
    clearInterval(this.timerId);
  }

  render() {
    return (
      <p>
        {this.props.label}: {this.state.now.toLocaleTimeString()}
      </p>
    );
  }
}

export default Clock;

What belongs in each method

  • constructor: call super(props) first, set this.state directly, and bind handlers if you are not using arrow-function class fields. Do not call setState here or start network requests.
  • render: return JSX based on props and state, and nothing else. It must be pure, with no timers, requests or setState calls, because React may call it many times.
  • componentDidMount: the component is now in the DOM. This is the place for fetching data, adding event listeners to window, or starting intervals.
  • componentDidUpdate(prevProps, prevState): runs after every re-render except the first. Compare old and new values before doing work.
  • componentWillUnmount: undo everything you started in componentDidMount.

The infinite update loop

The most damaging mistake in this area is calling setState inside componentDidUpdate without a condition. Setting state triggers an update, which calls componentDidUpdate again, which sets state again, and the component re-renders until React stops it with an error. Always wrap that call in a check such as if (prevProps.userId !== this.props.userId).

The second common bug is forgetting cleanup. If the interval above were not cleared, it would keep calling setState on a component that no longer exists, wasting memory and causing warnings in development.

Development mode runs some code twice

Under React's StrictMode in development, React deliberately mounts, unmounts and remounts components, and calls render-phase methods twice. This is meant to expose missing cleanup. If your log shows componentDidMount twice, that is expected; production builds do not do it.

How this maps to hooks

Function components handle the same moments with useEffect. The effect body plays the role of componentDidMount and componentDidUpdate, and the function it returns plays the role of componentWillUnmount. Understanding the class methods makes that mapping much easier, which is useful when you compare the two styles.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course