23

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?

Adi Sivasankaran
  • 518
  • 3
  • 6
  • 20
  • 1
    The docs cover this: https://facebook.github.io/react/docs/component-specs.html. I'm not sure what else you're looking for? – WiredPrairie May 05 '15 at 02:43
  • Here is an example of componentWillMount function: http://stackoverflow.com/questions/23123138/perform-debounce-in-react-js – xinyuan Aug 15 '15 at 04:12

5 Answers5

26

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 });
  }
Cymen
  • 14,079
  • 4
  • 52
  • 72
  • I've since written a datepicker in React inspired by Pikaday: https://github.com/cymen/react-daypicker – Cymen Sep 02 '17 at 21:25
5

componentDidMount only runs once and on the client side. This is important, especially if you're writing an isomorphic app (runs on both the client and server). You can use componentDidMount to perform tasks require you to have access to window or the DOM.

From Facebook's React Page

If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests, perform those operations in this method.

componentWillMount has fewer use cases (I don't really use it), but it differs in that it runs both on the client and server side. You probably don't want to put event listeners or DOM manipulations here, since it will try to run on the server for no reason.

Jon
  • 5,945
  • 4
  • 21
  • 31
  • @Jon- What do you mean "runs on the server side". Isnt react a client side technology? (I did see this stated in the docs as well and it confused me) – Dave Pile May 05 '15 at 09:22
  • 6
    Since React is javascript, one of the cool things about it is you can run the code in node as well as in the browser. This means you can have essentially the same code base for the server and the client. an example would be having a node express server running that takes an http request, runs react and the function renderToString, and then sends the resulting string as its response. https://github.com/mhart/react-server-example – Jon May 05 '15 at 15:22
  • @Jon that example doesn't actually make use of componentWillMount. It seems clear to me that it should be used in isomorphic web apps, but I have yet to see a single example that makes use of it. – dpwr Mar 14 '16 at 13:59
0

This is an example of an isomorphic web application that makes use of componentWillMount: https://github.com/coodoo/react-redux-isomorphic-example

However, I'm 99% certain that it runs the code inside componentWillMount for no reason on the server side (I think using componentDidMount to ensure it was only run client side would have made more sense) as the code which ensures that fetch promises are fulfilled before rendering the page is in server.js not inside the individual components.

There is discussion on per-component async fetching here: https://github.com/facebook/react/issues/1739 As far as I can tell, there is not a good use case for componentWillMount as far as isomorphism is concerned at least.

dpwr
  • 2,732
  • 1
  • 23
  • 38
0

In my project which is a dashboarding tool, I have used componentDidMount().

On home page previously saved dashboards appear on the sidebar. I make an ajax call within componentDidMount() of component rendering Homepage, so as to fetch list of dashboards asynchronously after the page has been rendered.

-2

Why React Life Cycle Methods?

Intend to use third-party (Ex D3.js) library with React Component


class Example extends React.component{
  constructor(){
    // init state
    // will be called only once
  }  
  componentWillMount(){
    // will be called only once
    // will not be triggered when re-rendering
    // usually will fetch data that is needed in order 
    // to render properly from other API
  }
  shouldComponentUpdate(){
      return false
      // will not re-render itself after componentDidMount(){}
  }
  render(){
    return (
      <div id="chart"></div>
    )
  }
  componentDidMount(){
    d3.select(".chart")
      .selectAll("p")
      // d3.js ........
      // d3.js ........
      // Usually, this will trigger React to re-render itself,
      // but this time will not because we have set 
      // shouldComponentUpdate to false
  }
}

Why React wants to do this?

Since rendering DOM is an expensive operation, React uses the layer of virtual DOM to update only DOM / DOMs that is/are different from previous state.

Wayne Chiu
  • 5,830
  • 2
  • 22
  • 19