Working with Data in Hooks

Learn how to pass data in custom Hooks and return the response to the component that called the Hook.

Passing data via custom Hooks

Passing data via custom Hooks is not a one-way street. In our first custom Hook example, we’ve seen that we can pass data into a custom Hook as a function parameter. The Hook can also return data that can then be used in the component. The form in which this data is returned from the Hook is entirely at the developer’s discretion. You can easily return strings, tuples, and entire React components or elements, or even a combination of these.

Accessing data from an API

Let’s assume that we want to access data from an API. We should parameterize the data that we want to access to make it easier to work with. Hooks can help us access the data in this case (it does not matter in which component it ends up being used) and then return it to the component that needs it. In this example, we’ll deal with user data from GitHub. So, a good name for our next custom Hook would be useGitHubUserData.

Custom Hooks

We pass a GitHub username to our custom Hook and obtain an object with all the relevant information from the user. The Hook itself deals with requesting the data from the GitHub API and will pass it to the component:

// useGitHubAccountData.js
import { useEffect, useState } from 'react';
import axios from 'axios';

const useGitHubAccountData = (account) => {
    const [accountData, setAccountData] = useState({});

    useEffect(() => {
        if (!account) {
            return;
        }

        axios.get(`https://api.github.com/users/${account}`).then((response) => {
            setAccountData(response.data);
        });
    }, [account]);

    return accountData;
};

export default useGitHubAccountData;

Once again, we’ve made use of the Hooks that we have already encountered: useEffect() and useState(). We’re using the state accountData to manage the GitHub user data inside of it. The effect is only ever executed if the username changes. Afterward, we request the user data for this account from the GitHub API, wait for the response, and then write the data of this response using setAccountData() into the state. Finally, we pass the state accountData back to the component that called the Hook in the first place.

Using custom Hooks inside function components

We can now safely access the data from this component and use it as we see fit. We will use a local API instead of the GitHub API in the example below. You may replace the local API with the official GitHub one to test it out:

Get hands-on with 1400+ tech skills courses.