How to learn react logo

These tutorials will give you a deeper understanding of React.js. Learn with examples from the Javascript UI library, covering the basics and the advanced.

Browse by tag:

Understanding the component life cycle

DOM

A component lifecycle method is a function that we can optionally define inside of our class based component. The series of events from birth (first render) to death (removal) is referred to as the component's life cycle.

Technically, the render method is a lifecycle function, howver, unlike all the other methods it is not optional. We absolutely have to define it and return some amount of JSX/content that becomes visible on the screen.

After that we're going to see a series of different life cycle methods being called at different points in time. First off, immediately after a component shows up on the screen of our browser componentDidMount is called.

After componentDidMount gets called our component essentially will sit around and wait for an update (in the form of calling setState). Anytime the component updates itself, another lifecycle method will be called automatically: componentDidUpdate. This method can be called a second, third, or fourth time - however many times our component gets updated.

Last, let's say we decide to stop showing this component on the screen, the componentWillUnmount method will be automatically called. This method will usually be used if we want to do some kind of cleanup after our component.

Below is an example with a few of the methods discussed above:

class App extends React.Component {
  constructor(props) {
    super(props);
  }
  
  componentDidMount() {
    console.log('The component just mounted (after rendering)...');
  }

  componentDidUpdate() {
    console.log('The component just updated...')
  }

  render() {
    console.log('The component rendered...')
    return (
      <div>Hello world!</div>
    );
  }
};

How To Learn React is designed and developed by me, Blake Fletcher. It is a project intended to share the things I learn while working with the UI library. As I build things, complete tutorials, read blog posts, and watch videos, I'll add to the site. I hope to eventually bring on other contributors. If interested, send me an email at blkfltchr@gmail.com.