Using React hooks to handle API calls
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
Below is the example of utilizing this API within component.
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.
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
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
References
Code reference https://codesandbox.io/s/react-hooks-for-api-qix4f
React Hooks documentation https://reactjs.org/docs/hooks-overview.html
Weather API https://www.metaweather.com
CORS proxy https://cors-anywhere.herokuapp.com
Codesandbox https://codesandbox.io/
Axios Hooks https://www.npmjs.com/package/@crushers-lab/axios-hooks
Github https://github.com/crushers-lab/axios-hooks