React Lifecycle: Why componentDidMount() is great for a smooth API call

When you are buying groceries to make dinner, you can’t start preparing the ingredients – chopping the onions, washing the radishes – until you’ve paid for the groceries and driven home, can you? This wouldn’t make sense. Similarly, in React we can’t make modifications to a component until it has been mounted. This is where the componentDidMount() lifecycle method comes in handy.

componentDidMount() can be used once the DOM has finished loading. This means that componentDidMount() is a great place to call functions that require the DOM to be rendered. For example, we don’t want to call a function that is dependent on an element that hasn’t loaded yet. componentDidMount() is a great lifecycle method because we don’t need to place the functions at a specific place in the document, as we would with VanillaJS. It is also great because it gives us higher organization, and we are able to see that everything within this method requires the DOM to be loaded.

One example of what we can use componentDidMount() for is API calls. If try to update a component’s state with an API call in render(), we will end up in an endless loop. This is because as the component is rendering it will setState() using the API, then the component will update because setState() has been called, then again the component will set state using the API, and on and on forever.

Graphic showing that if a React component renders, and the API sets the state during rendering, then the component re-renders, and on and on in an endless cycle.

If we call the API in componentDidMount(), the component will set state only once. This is because the component will mount, then the API will be called to set the state. The component will be updated, but now when it re-renders, it’s not calling fetch() again, because the component is already mounted. Pretty cool, right?

Graphic showing step-by-step process of React component mounting, followed by the API setting state, and finally the component updating

Now when we use componentDidMount(), we can rest assured that we’re back in our kitchen, before we start peeling the potatoes.

References

Ighodaro, N. (2018). “A begginer’s guide to the React component lifecycle.” [Web]. Pusher. Accessed 5 Nov 2020. Available at: https://blog.pusher.com/beginners-guide-react-component-lifecycle/#:~:text=The%20componentDidMount()%20method&text=That%20is%20after%20the%20HTML,sub%2Dcomponents%20have%20rendered%20properly.

Image Credit: Chopping Ingedients, Katie Smith

Subscribe to new blog posts