React Lifecycle methods --- where do you make your API calls?

React Lifecycle methods --- where do you make your API calls?
0

#1

Hi All,

I am learning react and am working on the FCC Leaderboard project. My plan is to have a DataTable component that will be stateful. This component will make the API call to get the FCC user / brownie points data (an array of objects).

My question is where within the component should I be making this API call? For this project I will only need to make the call once as once I have the data all I need to do is sort it and display it differently to the user.

My initial thought was to make the call in componentWillMount() but it seems like this function executes before every render() so I would be repeating API calls for no reason is this correct?

This blog post suggests making the API call in componentDidMount() stating that:

This method will be executed when the component “mounts” (is added to the DOM) for the first time. This method is only executed once during the component’s life.

This sounds like what I want but what I am not understanding is how this only runs once. How is the component not remounted to the DOM every time render() is called?

If anyone could shed some light on this I’d really appreciate it.

Thanks everyone


#2

Hi @Swoodend,

Yes, componentDidMount is exactly what you want. To answer your question…

The component IS remounted to the DOM every time render() is called. The FIRST time it is mounted, React invokes the componentDidMount lifecycle hook, then every subsequent time that the component is mounted, React invokes the componentDidUpdate lifecycle hook.

From the React docs:

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Hope that helps.

Regards,
Bill Sourour
devmastery.com


#3

Adding to what Bill Sourour said:

The good thing about using high-level API is that you don’t have to understand how the underlying low-level codes are implemented. The only thing you should care is what ReactDoc says about componentDidMount(). Always check the official documentation before any blog posts.

If you exactly want to know how it works, then the only thing you can do is to read the source code. But this can be intimidating as React is a sophisticated library. I’ve tried it but failed to understand how exactly they are calling component life cycle methods. (I’m a damn newbie :slight_smile:)


#4

@BillSourour @gunhoo93

Thank you very much for your help! Appreciate it! :slight_smile: