componentDidMount() v/s componnetWillMount() — React

Hima Chitalia
Coffee and Codes
Published in
2 min readSep 12, 2017
componentWillMount() v/s componenetDidMount() — React

When you are a learning any new language or a framework, everything seems little bury. This happened to me also when I started learning React Framework.

I had a hard time understanding difference between componentDidMount() and componentWillMount() methods. Now that I understand the difference, here is for anyone need little more clarity on these two methods:

componentWillMount() v/s componenetDidMount() — React

Use-case for the componentWillMount()

For example, if you want to keep the date of when the component was created in your component state, you could set this up in this method. Please keep in mind that setting state in this method won’t re-render DOM. This is important to keep in mind, because in most cases whenever we change the component’s state, a re-render is triggered.

componentWillMount() {
this.setState({ todayDate: new Date(Date.now())});
}

Use-case for the componentDidMount()

For example, if you were building a news app that fetches data on the current news and displays it to the user and you may want this data to be updated every hour without the user having to refresh the page.

componentDidMount() {
this.interval = setInterval(this.fetchNews, 3600000);
}

That’s it on this. Any suggestion or question, please feel free to write me at hima.chhag@gmail.com or in comment section below.

Happy Coding!

--

--