How to Fetch Data With React Hooks

To fetch data from your API using React hooks, you can introduce a custom useFetch hook that uses useState and useEffect internally:

import { useState, useEffect } from 'react'

const useFetch = url => {
    const [state, setState] = useState([null, false]);

    useEffect(() => {
        setState([null, true]);

        (async () => {
            const data = await fetch(url)
                .then(res => res.json());

            setState([data.body, false]);
    }, [url]);

    return state;

export default useFetch;
Copied to clipboard!

This function returns an array with two variables: A post object, and a loading flag. By default, on line:4, you can see that we start out with null and false. There's nothing loading. But then we set loading to true on line:7, and inside an anonymous async function, we fetch the result. Once the result comes back, we can populate it into the post variable that is returned.

Note that you can't make the callback of useEffect async directly. Therefore, you have to define a sepearate async function inside it. And of course, once the data is returned, we can set the loading state back to false. You can pass the url into the dependency array of the useEffect. This tells React to only rerun the effect when the URL changes. To use this hook, you can introduce it in your component the following way:

// After importing the useFetch hook
const Post = () => {
    const [post, loading] = useFetch('');
    if (loading) {
        return <Loading />

    return <PostBody content={post} />;
Copied to clipboard!

If you would like to see it in action, give it a try on Codesandbox

Try the hook on codesandbox
How to Fetch Data With React Hooks
If you would like to see more Webtips, follow @flowforfrank

If you are interested in reading more about React hooks, see more examples for custom hooks or just learn about the basics, make sure to check out the article below.

All You Need to Know About React Hooks
Remove ads
Remove ads

๐Ÿ“š Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. โ˜•

Get access Support us
Remove ads
Remove ads
Remove ads
๐ŸŽ‰ Thank you for subscribing to our newsletter. x This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.