Introduction
In this article, I am going to explain how to create a custom Hook for API calls in React.
React Hooks
It is a new feature that allows using React features without writing a class. Hooks are functions that help to use the state and lifecycle features in the React function components. Hooks do not work inside the class components. This feature has introduced in React 16.8.
We need to follow the below rules to use Hooks in the React
- Only call Hooks at the top level
Hooks should always be used at the top level of the React functions. Do not call Hooks inside the loops, conditions, or nested functions.
- Only call Hooks from React functions
Cannot call Hooks from regular JavaScript functions. Instead, Call Hooks from React function components. Hooks can also be called custom Hooks.
Custom Hooks
Custom Hooks are used for building common or reusable logic and these functions are prefixed with the word "use". Ex. useTestCustomHook.
I am using typescript for implementing the custom hook in React. I have two interfaces which are IRequestInfo and IResponseInfo.
IRequestInfo
IRequestInfo defines how the request format should be. It has below properties.
Headers
Request headers like authentication, content-type, etc.
Method
It represents the API Method such as "GET" or "PUT" or "POST" or "PATCH"
EndPoint
It is the API endpoint going to call.
RequestBody
Request Body for the API call. It is an optional one. Because the GET call doesn't have a request body.
export interface IRequestInfo {
Headers?: {};
Method: string; // "GET" or "PUT" or "POST" or "PATCH"
EndPoint: string;
RequestBody?: object;
}
IResponseInfo
IResponseInfo defines the format of the response and it has below two properties.
Data
It contains the response data or error.
hasError
It is true if the fetch is failure otherwise false. We can identify the API status using this property.
export interface IResponseInfo {
Data: any;
hasError: boolean;
}
I have created one custom hook function "useFetchCall".
Inside the "useFetchCall" hook,
- Used the fetch() function to call the API
- The hook has one argument for the initial request value.
- The hook has three return values
- response - It has the response of the API which is the IResponseInfo type.
- isFetching - It is true when calling the API and false once the response came from API
- setRequest - Set the request for API call which is IRequestInfo type.
- When calling the setRequest() function from any function component or other custom hooks, it will assign the request data to "requestInfo" local state inside the "useFetchCall" hook.
- Once value is assigned to "requestInfo" local state then, the useEffect() will be execute. Because, "requestInfo" has added as dependecy for that useEffect().
- The API calling logic will be executed inside of the useEffect().

Join the conversation! Your thoughts help the community grow.