Home > Back-end >  Reactjs call backend API only one time when component loads first time
Reactjs call backend API only one time when component loads first time

Time:02-24

I have a two react functional components: a) ParentComponent b) ChildComponent:

I am calling ChildComponent from ParrentComponent. In my ChildComponent I am calling an API to get data (Let Say Filters common data), now everytime I call ChildComponent from parents my APIs in ChildComponent gets called. However I just want these API calls only first time and then want to use the APIs response data for other rendors.

I have used useEffect, useCallback but seems I am not able to make it work.

CodePudding user response:

useEffect(() => {}, []) should run only on first render. If that doesn't work, you can always put your fetch in the parent component instead, and send down the data to the child component. In this way it will only load once.

CodePudding user response:

If you are calling the API with useEffect, it's gonna be execute everytime you call the ChildComponent. Instead, if you only want to call the API just one time, move the API call to the ParentComponent and send the response to the ChildComponent using params.

You can also use Context, but I think that is not a must in this case.

CodePudding user response:

Make a function to fetch Data and wrap it whit useCallback then call this function in UseEffect and add function to dependecies. It should run only in first render

useCallback will prevent infinite loop

  • Related