Using React hooks to handle API calls

Deepak Kumar T P
2 min readMay 24, 2020

React Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

useState hook used for local state management.
useEffect hook adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount

We can create custom hooks to extract component logic into reusable functions.
One of the common use case in any modern application is fetching data using API calls.
We can extract the logic required to make API calls to a react hook.

Below is the example of making a API call to a weather API to fetch weather forecast of a city. We will be using https://www.metaweather.com APIs and we are using a proxy to handle CORS https://cors-anywhere.herokuapp.com

https://gist.github.com/Deepak13245/a4da71679264054f675c6f13806a3ef2

Below is the example of utilizing this API within component.

https://gist.github.com/Deepak13245/d9a4bf4b6c623292dafd46318d5dfc22

reload function is used to reload data when clicked on button or initial render with useEffect

The problem with above code is we are writing some sort of business logic within the component which can be extracted into a hook and use that hook where ever the same business logic is required.
This makes component more readable and maintainable.

Below is the snippet to create a hook which extracts this business logic.

https://gist.github.com/Deepak13245/cb1af99bf129f753c192a94a86b3ba46

This file has exact same logic that we saw in component.
It returns two items data which contains data from API and reload function which can be called to reload data when ever required.

Now lets see how we can use this hook to simplify code inside component

https://gist.github.com/Deepak13245/c4a466ab2da0b2bf81c420a2d183bd1f

We simply call useWeather and use data and reload as required and this reduces almost 12 lines in component.
The complete business logic is moved to useWeather hook which can be used in multiple components

Below is the complete code available in Codesandbox

You can look into this repo or use this package to for advanced implementation

NPM :- https://www.npmjs.com/package/@crushers-lab/axios-hooks

GitHub :- https://github.com/crushers-lab/axios-hooks

--

--