How to Fetch Data With React Hooks

How to Fetch Data With React Hooks

Ferenc Almasi β€’ πŸ”„ 2021 June 30 β€’ πŸ“– 2 min read

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
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro