How to build your own React hook?

Published : 13th April 2020 | by @faisaljebali
#reactjs#hooks

In this tutorial, we will create a React hook that is responsible for fetching data from an external or internal API is a common use case for web applications. With react functional components, there are different hooks to fetch data. First of all, let's start by defining how we'd like to use our hook. Our React hook needs to meet the following requirements.

  • API URL for example : https://api.github.com/users/octocat/followers

  • it should return the states of loading, error and result

Creating the hook

We'll be using the new useState hook from React within our own hook, let's start by importing that and declaring our useFetchData function.

import React, {useState} from 'react'; function useFetchData(url, timeout) { const [data, setData] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(false); return {data, loading, error}; }

Now we need to implement the required functions.

Let’s write the function that fetches the data.

async function load() { setLoading(true); try { const result = await axios.fetch(url, {timeout: timeout}).data; setData(result); } catch (e) { setError(true); } setLoading(false); }

we use the axios library to make the actual request to the URL, and provide the timeout value

Now we need to implement initialization function.

function init() { setData([]); setLoading(true); setLoading(false) } async function load() { init(); ... }

Our React hook is complete! Let's see the full code of our hook.

import React, {useState} from 'react'; function useFetchData(url, timeout) { const [data, setData] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(false); function init() { setData([]); setLoading(true); setLoading(false) } async function load() { init(); setLoading(true); try { const result = await axios.fetch(url, {timeout: timeout}).data; setData(result); } catch (e) { setError(true); } setLoading(false); } return {data, loading, error, load}; } export default useFetchData;

This article showed how to implement a custom fetch data hook.

faisal jebali

Home page