DEV Community

Cover image for React useEffect fetching API

React useEffect fetching API

Shubham Tiwari on July 20, 2021

Hello everyone today i will show you how to fetch API in react js using 'useEffect'. Hooks are a new addition in React 16.8. They let you use stat...
Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

That fetch is going to happen 2x at the start. The first time when todos is [] and then it will happen again when it's the result of the fetch as the useEffect deps will have changed. Then actually doesn't it just keep going because the object is different in todos?

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

I am still learning so don't know much about in detail for now

Collapse
 
rbluena profile image
Rabii Luena

I admire you on the fact that you are still learning but you still want to each others from what you have learned so far. That is a winning attitude right there. I wanted to help but LUKE already did.

Thanks for sharing.

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Thank you

Collapse
 
j3ffjessie profile image
J3ffJessie

Great tutorial and setup. As others have pointed out you would want to leave out the dependency todos from your useEffect so that it doesn’t loop but overall you were thorough with your explanation and I believe you understand useEffect pretty well. Thank you for writing this article.

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

I am still at the learning stage and I even don't have 6-8 months of experience for now. So,kind of newbie here

Collapse
 
j3ffjessie profile image
J3ffJessie

We all start there and you are grasping concepts very well. Keep up the hard work and you will do fine. Posting articles like this and getting feedback will help as well. You are doing great. Keep pushing forward.

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Thank you

Collapse
 
tmartinri profile image
tmartin-ri

I would say that if you only want it to run the first time your component loads you should leave the useEffects dependency empty but at my work we use exhaustive deps on the linter and it would throw an error for emptying the dependency array. Instead I would recommend putting the fetch in an if statement that checks todos.length === 0

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Yes it will also work good

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Thank you for this
I will try these things also

Collapse
 
dhwajsharma profile image
Dhwaj Sharma

Thanks mate

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

welcome buddy

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

But when I leave it empty it throws error of empty dependency