React Usefetch

Posted on  by admin

It’s very common to fetch data when the user goes to a certain page. We also use common logic when fetch that data. There’s also a fair amount of boilerplate/logic that crowds our components and it’s not very DRY (Don’t Repeat Yourself). These are all good reasons to make a custom hook.

We can outsource that boilerplate/logic into one separate file. That file will hold the function (hook), which will return for us what we need to use in our components.

Conclusion

  • In this example, I’ll use the useState hook to keep track of the loading state, any error, and the data.
  • I’ll use the useEffect hook to run all of that code.
  • Lastly, I’m using axios to fetch the data, and a cancel token to cancel any unfinished requests that we don’t need anymore.
  • That’s a lot of code.
  • Let’s move most of it.
  • We’ll create another file called useFetch.js.

You want to start the name of a custom hook with “use” so that React knows to treat it like a hook.

Let’s copy over the import statements, all 3 useStates, and the useEffect function.

You may have noticed some changes. First of all, the function (which is our hook), is named useFetch. It recieves a parameter which is the url we want to get data from.

We also changed setQuote to setData, making it more versatile.

Notice that we also check for multiple responses to make it more flexible as well.

3. Make it return a loading state

Lastly, our useFetch function (hook) returns our data, loading, and any error. I put those in an object so we can use object destructuring when accessing those in our component.

That way, the order doesn’t matter when we destructure them, and we can rename them if we want.

I’ll show you that next. So, back in our App component, we’ll import our useFetch hook from useFetch.js, and pass in the url we want to fetch data from.

4. Cleanup

We’ll use object destructuring to access what we need. Lastly, we’ll rename data to quote. Muuuuuch cleaner 😎. Custom hooks are very useful for cleaning up your code.

You can use React hooks inside your custom hooks (they’re all functions after all!

You can encapsulate a lot of repetitive logic, then return what you need from the custom hook.

brimblehq/use-fetch

I have a YouTube video if you want to see it in action. If you like learning about similar topics, feel free to check out my YouTube or Instagram. Hope this helped somebody and thanks for reading!

This guide is to show you how to create a simple react hook for data fetching (with revalidation).

When fetching data for your react applications, you'd usually use both useState and useEffect, with values like loading, data and error e.g This example, this hook is to help abstract that functionality into one simple hook that can be used anywhere and multiple times.

Why useFetch?

We would be using the create-react-app boiler template for typescript and the only external library we would be using is axios for data fetching.

Open up your terminal and type in the following commands. Change into the directory and install axios. Within the src directory delete the following file (because they aren't needed).

Within the src directory create another directory called hooks, this is where our hook will reside. Your file structure should look something like this.

Within the hooks directory create a file called useFetch.tsx.

⏰ Adding Interval revalidation

Type in the following inside the useFetch file. The hook takes in a prop url, which is the API url at which we want to fetch data from.

It has two states data and error which are used to store data gotten from the API and check for errors respectively. We created a separate function for fetching the data called fetch and wrapped it within a useCallback hook, Visit here to see the reason why we used a useCallback hook.

Then we simply used a useEffect hook to run the fetch function as soon as the hook is mounted 🙂.

In just five minutes

The hook returns data, error and revalidate which is the fetch function for when we want to programmatically revalidate the data. To use the hook we simply just import it and extract its values.Within the App.tsx.

You might need to fetch data from your API every 5 seconds for revalidation (ensuring your data is up-to-date). We need to add some modifications to our useFetch hook.

Lets and more props. revalidate will be a boolean to check if we want to implement interval revalidation or not, interval will be the time taken between every revalidation (in seconds).

We'll create a state called revalidateKey that we will change on every interval which will be added to our useEffect dependency array.

🎣 Custom useFetch hook

Adding this to our dependency array will ensure that the function within our useEffect will run everytime the revalidateKey changes.

🕺 Setting up the project

To change the revalidateKey, we will create a new useEffect that has a setInterval. Our useFetch hook should then look something like this.

Using the useFetch hook ✨. This hook uses only the GET method, and Graphql uses POST method for data fetching.

To make the hook more dynamic you can add more props like isGraphql and query, isGraphql will be a boolean to check if its Graphql or REST so you can have a condition in your hook to use axios.post() instead of axios.get() and query for the graphql query.