Build Your Own Custom React Hook.

Build Your Own Custom React Hook.

In almost every front-end application we make API calls. Two most popular ways of making HTTP requests are either by using Fetch API or Axios library.

In this article, I’ll explain how to write a custom hook for Axios in React. By following this method, we can avoid the repetition of the code in multiple places. Here are the following steps to implement it, for this example we will be using Chuck Norris API.

1. Calling API using component.

In our App component, we will just call a get API to get a random joke. For this, we are using the useEffect hook. The basic API call from an App component will look something like this:

import { useEffect } from 'react';
import axios from 'axios';

const App = () => {
    const fetchData = () => {
        axios
            .get('https://api.chucknorris.io/jokes/random')
            .then((res) => {
                console.log(res);
            })
            .catch((err) => {
                console.log(err);
            });
    };

    useEffect(() => {
        fetchData();
    }, []);

    return (
          <div className='app'>
              //render it into UI
          </div>
       );
};

export default App;

2. Adding states to our app.

Till now, we are just logging the response coming from API. Let’s use React’s states to save our response and error.

import { useState, useEffect } from 'react';
import axios from 'axios';

const App = () => {
    const [response, setResponse] = useState(null);
    const [error, setError] = useState('');

    const fetchData = () => {
        axios
            .get('https://api.chucknorris.io/jokes/random')
            .then((res) => {
                setResponse(res.data);
            })
            .catch((err) => {
                setError(err);
            })
    };

    useEffect(() => {
        fetchData();
    }, []);

    return (
        <div className='app'>
           //render it into UI
        </div>
    );
};

export default App;

3. Move logic to a separate file to create a custom React Hook

Let's create a custom hook called useAxios which will fetch API data for us, custom hooks are just another component, which returns values instead of JSX. You can read more about custom hooks here.

So our useAxios hook will look like this after adding all the React states and API calls

// useAxios hook

import { useState, useEffect } from 'react';
import axios from 'axios';

const useAxios = ({url}) => {
    const [response, setResponse] = useState([]);
    const [error, setError] = useState('');

    const fetchData = () => {
        axios
            .get(url)
            .then((res) => {
                setResponse(res.data);
            })
            .catch((err) => {
                setError(err);
            })
    };

    useEffect(() => {
        fetchData();
    }, []);

    // custom hook returns value
    return { response, error };
};

If you see created a custom hook. The only difference is this hook is returning us 2 values, response, and error.

4. Make the hook dynamic

Now we’re ready to use the custom Hook inside the component. Remove unnecessary code and store results of the Hook in variables:

import React from "react";
import { useAxios } from "./useAxios ";

const App= () => {

  const { response , error } = useAxios (
    "https://api.chucknorris.io/jokes/random",
  );

  return (
    <div>
      data.map((user) => (
          <div key={user.id}>
            <h3>{user.name}</h3>
            <p>{user.email}</p>
          </div>
        ))
    </div>
  );
};

In useAxios(), we’re passing URL for fetching users.

Now our data will be stored in data and the component will re-render as soon as data is fetched or an error occurs. You can handle errors as well.

I hope you all understood about custom hooks. Thanks for reading!!! Bye, Good Luck

Did you find this article valuable?

Support Suyash Pradhan by becoming a sponsor. Any amount is appreciated!