DEV Community

Cover image for React Hooks for Data Part 1 - Fetching Data

React Hooks for Data Part 1 - Fetching Data

bdbch on July 19, 2019

So the large hype on React Hooks is over and the community isn't talking about them that much anymore. But seriously hooks are beasts. In this post...
Collapse
 
2ezpz2plzme profile image
Steven Liao

I had recently implemented something similar to this.

const [loading, setLoading] = useState(false)

I did the same thing, initializing loading state to false. However, my coworkers argued that it could be

const [loading, setLoading] = useState(true)

because the Hook will eventually set loading state to true any way. I argued that the Hook isn't actually fetching until the effect runs, which is why I initialized loading state to false. I eventually gave in and initialized loading state to true because I felt like we were bikeshedding.

Anyway, what do you think?

Collapse
 
2ezpz2plzme profile image
Steven Liao

Eventually found one good thing about initializing loading state to true. If the component using this custom fetch Hook rendered some other content, it won't flicker. In your case, this shouldn't happen though since BookList isn't rendering anything other than the fetched books.

Collapse
 
bdbchgg profile image
bdbch

That's true! I'll update the post and add your note to it.

Collapse
 
avxkim profile image
Alexander Kim

How do you deal with this part:

if (loading) return <div>Loading...</div>

This causes annoying flashing, before promise is resolved. Is there a way to show this loader inside actual markup, instead of this single element with Loading...?

Collapse
 
monfernape profile image
Usman Khalil

Loved your explanation. Can you describe useEffect in detail in next post. I couldn't understand the use case

Collapse
 
bdbchgg profile image
bdbch

Hey, thank you a lot.

I won't write about useEffect in the next post but I just wrote a quick explanation here:
dev.to/bdbch/a-quick-explanation-o...

Let me know if it helped you! :)

Collapse
 
accrepo1 profile image
acc-repo1

Nice Article...

useful info, remarkable clarity, one small typo (closing paren):

    books.map(book => <div key={book.id}>{book.title}</div>);
Collapse
 
bdbchgg profile image
bdbch

Thank you very much! Fixed!

Collapse
 
bdbchgg profile image
bdbch

I'd say because of the comments which are cluttering the actual source code and the new way to update states etc.

Collapse
 
sebastienlorber profile image
Sebastien Lorber

This code is subject to race conditions. Check my post about that subject here: dev.to/sebastienlorber/handling-ap...

Collapse
 
kimsean profile image
thedevkim • Edited

what would be the pros and cons on using fetch vs axios ?