While building my React and Redux project in bootcamp, I had a difficult time understanding the fundamental differences between the
componentDidMount() methods. I kept getting frustrated when one would work, yet I didn’t understand how or why.
One big snag that I didn’t realize until an online study group session is that
componentWillMount() was deprecated in 2018. While you can continue to use it (until React 17.0), it isn’t best practice because it is not safe for async rendering. If you do choose to continue to use it, you should use
Using a fetch call within
componentWillMount() causes the component to render with empty data at first, because
componentWillMount() will NOT return before the first render of the component.
componentWillMount() to finish, so the component continues to render.
With all that being said, you would need to to create a component that still looks presentable without the data that you are hoping to display. There is no way (not even a timer) to stop the component from rendering until the data is present.
When I was building my project, I didn’t know about the deprecation of
componentWillMount() and I didn’t understand why I kept getting the “cannot read property ‘map’ of undefined” error. I was so confused because I had an array and it should be getting populated by data, but it wasn’t.
Turns out this makes complete and total sense since the component is rendered with empty data at first, so the array was empty and couldn’t be iterated over. It was only at this point that I learned that it is best practice to use
The best place to make calls to fetch data is within
componentDidMount() is only called once, on the client, compared to
componentWillMount() which is called twice, once to the server and once on the client. It is called after the initial render when the client received data from the server and before the data is displayed in the browser. Due to the fact that the data won’t be loaded until after the initial render, the developer NEEDS to set up the components initial state properly.
On a side note, with
componentDidMount() you can use a timer and have the data updated every so often without the user ever having to refresh the page. I’d say that is a really neat feature that can be useful in projects/websites.
Once I learned that I should be using
componentDidMount(), my project really came to life. Everything else was working properly and that was my final error to fix. It was amazing learning that it was this simple of a problem, it just seemed complex to me at first. The more I write about it, the more it becomes clear. I hope that by the time you’ve gotten to this point you feel like you have a better grasp on the topic as well. If you need any extra information, please feel free to look at my resources, they are great articles!