Register to get access to free programming courses with interactive exercises

Component lifecycle JS: React

When you use React correctly, most components consist of the render method and event handlers:

class ArticleItem extends React.Component {
  handleClick = (e) => {
    e.preventDefault();
    const { onClick } = this.props;
    onClick();
  }
  render() {
    const { name, description, link } = this.props;
    return (
      <div>
        <a href="{link}" onClick={this.handleClick}>{name}</a><br />
        <div>{description}</div>
      </div>
    );
  }
}

But not all problems are solved so easily. Imagine a <Clock />, component that simulates a digital clock in hh:mm:ss format. Template:

class Clock extends React.Component {
  render() {
    const currentTime = new Date();
    return (
      <div>{currentTime.toLocaleTimeString()}</div>
    );
  }
}

This component displays the current time. Now we have to figure out how to update it. A clock, unlike conventional components, does not expect action from the user. They update themselves every second. We end up with a chain: an event happens => the current time changes => React calls render and changes the DOM. So, the state is initialized by the current time:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }
  render() {
    const { date } = this.state;
    return (
      <div>{date.toLocaleTimeString()}</div>
    );
  }
}

The component still shows the current time at the time the component is rendered/re-rendered, but it's now ready to change. Time refers to periodic events for which timers are used. For <Clock /> setInterval setInterval is fine. The timer must be set immediately after rendering the clock and must be cleared when the component is removed from the Item Tree.

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

Where do I start the timer? render render is called whenever the state changes, so it's not the right option. Because then <Clock /> will start a new timer every second. The constructor seems like a more appropriate place, but there's something else here. Calling the constructor and rendering the clock in the DOM tree are generally independent events. Look at this code:

// The constructor is called
const clock = <Clock />;

// Something's taking a long time.

// Rendering
const root = createRoot(document.getElementById('root'));
root.render(clock);

This clock isn't in the DOM tree yet, but it's already up and running. Is it worth worrying about? Yes, this behavior is extremely unexpected, it interferes with testing and wastes CPU time. In addition, the constructor doesn't with removing the timer in any way.

Each React component goes through several stages in its life: it's created, added to the DOM, receives props, and is finally removed from the tree. This process is called the Component Lifecycle. React provides a set of methods that allow you to integrate into this process. For example, it makes sense to start the clock immediately after rendering it. The componentDidMount method can help with this. It's called immediately after rendering a component. It happens exactly once.

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

  componentDidMount() {
    // The timer identifier is saved
    this.timerId = setInterval(() => this.setState({ date: new Date() }), 1000);
  }

  render() {
    const { date } = this.state;
    return (
      <div>{date.toLocaleTimeString()}</div>
    );
  }
}

Note how the timer is stored inside the object. It's not involved in the view, so there's no need to use the state.

Now you need to clear the timer. The method componentWillUnmount, which is executed just before the component is removed from the DOM, is good for this.

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

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

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

  render() {
    const { date } = this.state;
    return (
      <div>{date.toLocaleTimeString()}</div>
    );
  }
}

The clock now looks finished.

So, you've learned two methods to build into a component's lifecycle, but there are many more. They're divided into three independent groups:

Mounting

These methods are called when the object is created and placed into the DOM.

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

Updating

Updating can occur when properties or states change. These methods are called during rerendering.

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

Unmount

There's one method in this group. It's called when a component is removed from the DOM.

  • componentWillUnmount()

This number of methods can be explained by the complexity of actual development. But, in practice, only a few are used regularly. Such methods include componentDidMount. It can be used to set timers, make AJAX requests, and change the DOM to bypass React. The latter is necessary when integrating with third-party libraries.


Recommended materials

  1. State and Lifecycle

Hexlet Experts

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.