Building a simple react hook api call with typescript

I recently started building my own hooks in react and I wanted to share one that found particularly useful.

Making api calls is something I do frequently, so one of the first hooks I set out to make was a simple hook that makes an api call, returns data, or an error message if something goes wrong.

Here is the full hook file, I’ll spend the rest of the article going through it pice by piece.

The first line of the hook is one of the most important

the [(id: string) => void, User, string] specifies all the return types that the hook provides. Typescript wont complain if you don’t provide this, but without it your return types will be misinterpreted and you wont be able to call the hook.So be sure to always specify your return types for functions.

The second part specifies the data we want to to return.

Thirdly, we have a simple asynchronous function to go and fetch our user.

Lastly, we have our array of items we want to return. Note how each value from left to right matches the return types in the first section.

And that’s all there is to it. Now you can import the hook and call it.

You can find a link to a demo sandbox here:

This is a pretty simple example, in my next article I will show to make this hook generic so you could use it for multiple api calls.

Former golf instructor turned software engineer. 4 years ago I left my job teaching golf in Beijing to pursue my passion for writing code.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store