Building Custom React Hooks for Calling APIs

Nelson Ho
3 min readApr 20, 2023

React hooks are a powerful feature introduced in React 16.8 that allow us to use state and other React features in functional components. They can help us keep our code clean and modular by extracting logic into reusable pieces.

One of the most common uses of custom hooks is to encapsulate functionality that is used across multiple components. In this tutorial, we’ll look at how to build custom React hooks, and how to use them in our components.

Creating a Simple Custom Hook

Let’s start with a simple example of a custom hook that manages a counter. This hook will maintain a count state and provide functions for incrementing and decrementing it.

First, let’s create a new file for our hook, useCounter.tsx:

useCounter hook

Here, we’re using the useState hook to create a state variable for our count, and the useCounter hook takes an initial value as an argument. The increment and decrement functions simply update the count by adding or subtracting 1.

Now, we can use this custom hook in our components like this:

Implementing useCounter hook

We can see here that we’re using the useCounter hook to create our count state and increment/decrement functions, and then rendering the state and buttons in our component.

Using Axios with Custom Hooks

Another common use case for custom hooks is making API calls with Axios. Let’s create a new hook that fetches data from an API endpoint and returns the response data. In case you’re new to front end developer, here’s an article discussing the benefits of Axios over the built-in fetch api.

First, let’s install Axios:

npm install axios
-----or-----
yarn add axios

Next, let’s create our custom hook, useApi.tsx:

useApi custom hooks using Axios

Here, we’re using the useState hook to manage the state for our API response data, loading status, and error. The useApi hook takes a URL and Axios options as arguments, and uses axios to make the API call and update the state accordingly.

Implementing useApi custom hook

Here, we import the useApi hook from our useApi.ts file and call it with the endpoint we want to hit and the HTTP method we want to use. The hook returns an object containing the current state of the API call, as well as a callApi function that we can use to trigger the call.

We then create a handleClick function that calls callApi when a button is clicked, and conditionally render loading, data, and error states based on the current state of the API call.

And that’s it! With this simple custom hook, we can easily handle API calls across our entire application.

File structure for our custom hook:

src/
|- hooks/
| |- useApi.ts
|- components/
|- MyComponent.tsx

I hope this gives you an idea of how powerful and flexible custom hooks can be in a React application. Happy coding!

--

--

Nelson Ho

Frontend Developer, Polyglot (Chinese, Japanese, Sanskrit, Tibetan), Acupuncturist