Tutorial

Create a Custom useFetch() React Hook

Draft updated on Invalid Date
author

Chris Nwamba

Create a Custom useFetch() React Hook

This tutorial is out of date and no longer maintained.

Introduction

A custom hook is a JavaScript function with a unique naming convention that requires -

  1. the function name to start with use and
  2. the function may call other Hooks

The whole idea behind custom hooks is just so that we can extract component logic into reusable functions.

Often times as we build out React applications, we see ourselves writing almost the same exact codes in two or more different components. Ideally what we could do in such cases would be to extract that recurrent logic into a reusable piece of code (hook) and reuse it where the need be.

Before hooks, we share stateful logic between components using render props and higher-order components, however, since the introduction of hooks and since we came to understand how neat they make these concepts, it no longer made sense to keep using those. Basically, when we want to share logic between two JavaScript functions, we extract it to a third function possibly because both components and hooks are equally just functions.

Abstracting fetch into useFetch()

The rationale behind this move is not different from what we have already explained above. Compared to using the native fetch API out of the box, abstracting it into the useFetch hook gives us a one-liner ability, more declarative code style, reusable logic and an overall cleaner code as we’ll see in a minute. Consider this simple useFetch example:

const useFetch = (url, options) => {
  const [response, setResponse] = React.useState(null);
  useEffect(async () => {
      const res = await fetch(url, options);
      const json = await res.json();
      setResponse(json);
  });
  return response;
};

Here, the effect hook called useEffect is used to perform major functions —

  1. fetch the data with the native fetch API and
  2. Set the data in the local state of the component with the state hook’s update function.

Also, notice that the promise resolving happens with async/await.

Avoiding reference loops

The effect hook runs on two occasions — When the component mounts and also when the component updates. What this means is, if nothing is done about the useFetch example above, we will most definitely run into a scary recurrent loop cycle. Why? Because we are setting the state after every data fetch, as a result, when we set the state, the component updates and the effect runs again.

Obviously, this will result in an infinite data fetching loop and we don’t want that. What we do want, is to only fetch data when the component mounts and we have a neat way of doing it. All we have to do is provide an empty array as a second argument to the effect hook, this will stop it from activating on component updates but only when the component is mounted.

  useEffect(async () => {
      const res = await fetch(url, options);
      const json = await res.json();
      setResponse(json);
  }, []); // empty array

The second is an array containing all the variables on which the hook depends on. If any of the variables change, the hook runs again, but if the argument is an empty array, the hook doesn’t run when updating the component since there are no variables to watch.

useEffect’s return error

You may have noticed that in the effect hook above, we are using async/await to fetch data. However, according to documentation stipulations, every function annotated with async returns an implicit promise. So in our effect hook, we are returning an implicit promise whereas an effect hook should only return either nothing or a clean-up function.

So by design, we are already breaking this rule because —

  1. We are not returning nothing
  2. A promise does not clean up anything

As a result, if we go ahead with the code as is, we will get a warning in the console pointing out the fact that useEffect function must return a cleanup function or nothing.

Warning: An effect function must not return anything besides a function, which is used for clean-up.

It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:


useEffect(() => {
  async function fetchData() {
    // You can await here
    const response = await MyAPI.getData(someId);
    // ...
  }
  fetchData();
}, [someId]); // Or [] if effect doesn't need props or state

Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching

Simply put, using async functions directly in the useEffect() function is frowned at. What we can do to fix this is exactly what is recommended in the warning above. Write the async function and use it inside the effect.

React.useEffect(() => {
    const fetchData = async () => {
      const res = await fetch(url, options);
      const json = await res.json();
      setResponse(json);
    };
    fetchData();
  }, []);

Instead of using the async function directly inside the effect function, we created a new async function fetchData() to perform the fetching operation and simply call the function inside useEffect. This way, we abide by the rule of returning nothing or just a cleanup function in an effect hook. And if you should check back on the console, you won’t see any more warnings.

Handling errors

One thing we haven’t mentioned or covered so far is how we can handle error boundaries in this concept. Well, it’s not complicated, when using async/await, it is common practice to use the good old try/catch construct for error handling and thankfully it will also work for us here.

const useFetch = (url, options) => {
  const [response, setResponse] = React.useState(null);
  const [error, setError] = React.useState(null);
  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch(url, options);
        const json = await res.json();
        setResponse(json);
      } catch (error) {
        setError(error);
      }
    };
    fetchData();
  }, []);
  return { response, error };
};

Here, we used the very popular JavaScript try/catch syntax to set and handle error boundaries. The error itself is just another state initialized with a state hook so whenever the hook runs, the error state resets. However, whenever there is an error state, the component renders feedback to the user or practically you can perform any desired operation with it.

Setting loading indicators

You may already know this, but I still feel that it’ll be helpful to point out that you can use hooks to handle loading states for your fetching operations. The good thing is, It’s just another state variable managed by a state hook so if we wanted to implement a loading state in our last example, we’ll set the state variable and update our useFetch() function accordingly.

const useFetch = (url, options) => {
  const [response, setResponse] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(false);
  React.useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        const res = await fetch(url, options);
        const json = await res.json();
        setResponse(json);
        setIsLoading(false)
      } catch (error) {
        setError(error);
      }
    };
    fetchData();
  }, []);
  return { response, error, isLoading };
    };

Usage

We cannot complete this tutorial without working on a hands-on demonstration to put everything we’ve talked about in practice. Let’s build a mini-app that will fetch a bunch of dog images and their names. We’ll use useFetch to call the very good dog API for the data we’ll need for this app.

First, we define our useFetch() function which is exactly the same as what we did before. We will simply reuse the one we created while demonstrating error handling above to explain the data fetching concept in practice since it already has most of the things we’ll need.

const useFetch = (url, options) => {
  const [response, setResponse] = React.useState(null);
  const [error, setError] = React.useState(null);
  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch(url, options);
        const json = await res.json();
        setResponse(json);
      } catch (error) {
        setError(error);
      }
    };
    fetchData();
  }, []);
  return { response, error };
};

Next, we create the App() function that will actually use our useFetch() function to request for the dog data that we need and display it on screen.

function App() {
  const res = useFetch("https://dog.ceo/api/breeds/image/random", {});
  if (!res.response) {
    return <div>Loading...</div>
  }
  const dogName = res.response.status
  const imageUrl = res.response.message
  return (
    <div className="App">
      <div>
        <h3>{dogName}</h3>
        <div>
          <img src={imageUrl} alt="avatar" />
        </div>
      </div>
    </div>
  );
}

Here, we just passed the url into the useFetch() function with an empty options object to fetch the data for the cat. It’s really that simple, nothing elaborate or complex. Once we’ve fetched the data, we just extract it from the response object and display it on screen. Here’s a demo on Codesandbox:

https://codesandbox.io/s/nostalgic-hopper-qsl0p

Conclusion

Data fetching has always been an issue to contend with when building frontend-end applications, this is usually because of all the edge cases that you will need to account for. In this post, we have explained and made a small demo to explain how we can declaratively fetch data and render it on screen by using the useFetch hook with the native fetch() API.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Chris Nwamba

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.