Search⌘ K

Lifecycle Methods in Practice

Explore React lifecycle methods by implementing a component that updates its state every second. Understand how componentDidMount and componentWillUnmount manage intervals and state changes, ensuring proper rendering and cleanup in React applications.

Implementing lifecycle methods

Let’s have a look at how lifecycle methods behave in a simple component. The code implements a component that updates its own state every second and displays the current time. As soon as the component mounts, an interval is started which updates the state of our component in the componentDidMount() method. A re-render is triggered, and the current time is shown again.

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import Clock from './app.js';

ReactDOM.render(
  <Clock />, 
  document.getElementById('root')
);

setState()

We see that the lifecycle methods componentDidMount() and componentWillUnmount() ...