0 votes
in ReactJS by
Is it good to use setState() in componentWillMount() method?

1 Answer

0 votes
by

Yes, it is safe to use setState() inside componentWillMount() method. But at the same it is recommended to avoid async initialization in componentWillMount() lifecycle method. componentWillMount() is invoked immediately before mounting occurs. 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 async calls for component initialization happened in componentDidMount() instead of componentWillMount().

componentDidMount() {

  axios.get(`api/todos`)

    .then((result) => {

      this.setState({

        messages: [...result.data]

      })

    })

}

Related questions

0 votes
asked Nov 3, 2023 in ReactJS by AdilsonLima
0 votes
asked Dec 19, 2023 in ReactJS by john ganales
...