What is the purpose of having functions like componentWillMount in React.js?

Adi Sivasankaran picture Adi Sivasankaran · May 5, 2015 · Viewed 12k times · Source

I have been writing components in React.js recently. I have never had to use methods like componentWillMount and componentDidMount.

render is indispensable. getInitialState and other helper methods I wrote also come in handy. But not the two aforementioned lifecycle methods.

My current guess is that they are used for debugging? I can console.log out inside them:

componentWillMount: function() {
  console.log('component currently mounting');
},

componentDidMount: function() {
  console.log('component has mounted');
} 

Are there any other uses?

Answer

Cymen picture Cymen · May 5, 2015

componentDidMount is useful if you want to use some non-React JavaScript plugins. For example, there is a lack of a good date picker in React. Pickaday is beautiful and it just plain works out of the box. So my DateRangeInput component is now using Pickaday for the start and end date input and I hooked it up like so:

  componentDidMount: function() {
    new Pikaday({
      field: React.findDOMNode(this.refs.start),
      format: 'MM/DD/YYYY',
      onSelect: this.onChangeStart
    });

    new Pikaday({
      field: React.findDOMNode(this.refs.end),
      format: 'MM/DD/YYYY',
      onSelect: this.onChangeEnd
    });
  },

The DOM needs to be rendered for Pikaday to hook up to it and the componentDidMount hook lets you hook into that exact event.

componentWillMount is useful when you want to do something programatically right before the component mounts. An example in one codebase I'm working on is a mixin that has a bunch of code that would otherwise be duplicated in a number of different menu components. componentWillMount is used to set the state of one specific shared attribute. Another way componentWillMount could be used is to set a behaviour of the component branching by prop(s):

  componentWillMount() {
    let mode;
    if (this.props.age > 70) {
      mode = 'old';
    } else if (this.props.age < 18) {
      mode = 'young';
    } else {
      mode = 'middle';
    }
    this.setState({ mode });
  }