Recommended Way to Call Method: componentWillMount vs componentDidMount?

Did search and found several StackOverflow answer use componentWillMount. However, Facebook itself uses componentDidMount to call jQuery Ajax. Both works!

How do you decide which one to use? Is there recommended way for meteor specific? I can’t find on Meteor Guide.

As you guess, I’m new in Meteor and React.

Thank you!

It up to you like do calling ajax before or after render content. I prefer componentDidMount

Prefer componentWillMount, unless you need access to the rendered DOM, in which case use componentDidMount. This is, I think, a pure React question, so you can find better guidance there.

1 Like

Agreed with this. Unless you need access to the component’s DOM, I think componentWillMount is the way to go.

1 Like

Not a directly related topic but you should also note that the React community seems now to prefer constructor over componentWillMount.

3 Likes

Have you tried it (ajax from constructor) and liked it, or are you just saying what you’ve heard? I saw the same buzz, tried it, didn’t like it. Most significantly, this.props is undefined in the constructor, so if the ajax call is dependent on, say, a passed-in key of an object to be gotten via ajax, you’re SOL. Similarly, if you’re using Redux, no props means no dispatch (at least by normal means). If any of the folks who “hearted” this have better guidance on when and why the constructor’s better, or on workarounds for the issues I raised above, I’d be happy to hear - all I have is more of this kind of vague “I heard that” second-hand recommendation, with no motivation and no warning about the gotchas.

constructor takes props as argument.

constructor(props) {
  super(props); 
  callAPIwithAProp(props.value);
}

the whole idea of React is to construct a component out of props. This.props will of course be undefined because it is passed in by the user

1 Like

constructor does receive the props

constructor(props) {
  super(props)
  console.log(props)
}

That’s how a class constructor works whether or not it is react related.