is it good to use setState() in the componentWillMount() method? in REACT

Practice



It is recommended to avoid asynchronous initialisation in the

componentWillMount()
lifecycle method.
componentWillMount()
is invoked immediately before mounting. It is called before
render()
, therefore setting state in this method will not trigger a re-render. Avoid introducing any side effects or subscriptions in this method. We need to make sure that
componentDidMount()
instead of asynchronous calls to initialise the component happened during initialisation
componentWillMount()
.
componentDidMount() {
  axios.get(`api/todos`)
    .then((result) => {
      this.setState({
        messages: [...result.data]
      })
    })
}

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Scripting client side JavaScript, jqvery, BackBone"

Terms: Scripting client side JavaScript, jqvery, BackBone