Today we are briefly going to talk about the mounting lifecycle.

Class based component lifecycle methods

Mounting

This is the process a component goes through to get instantiated.

By using the constructor() we initialize state by setting the watch state to a new date.

This is pretty self explanatory from the docs so adding it here for reference.

If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

Typically, in React constructors are only used for two purposes:

Initializing local state by assigning an object to this.state.
Binding event handler methods to an instance.
You should not call setState() in the constructor(). Instead, if your component needs to use local state, assign the initial state to this.state directly in the constructor:

The render() will then do the initial render.

The componentDidMount() will run the setInterval. In this lifecycle method, this is where we put other calls such as:

  • Calling a Web API
  • Subscribe to promises
  • Start timers (like in our example)

So to recap this is the order of a lifecycle in a class based component.

  • constructor
  • render
  • componentDidMount
class Watch extends React.Component {
  constructor(props) {
    super(props);
    console.log("ctor");
    this.state = { date: new Date() };
  }
   componentDidMount() {
    console.log("componentDidMount");
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }
   render() {
    console.log("render");
    return (
      <div>
        <h1>Hello, friend!</h1>
        <h2>My watch says it's {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }

Conclusion 🐒

We spoke about mounting today, next time on jean think we will discuss the next stages.

  • Mounting
  • Updating
  • Unmounting
  • Error Handling

Resources: