Learn to build your first custom Hook with simple and easy steps. Learn how to build a custom useFetch React Hook. We will create a custom hook named “useFetch” which will make the API calls, as well as manage the loading and error state. This hook can be re-used whenever we want to fetch data using API calls with no need of managing the loading and error states individually everywhere.

Before we begin to create our first custom hook, we need to have some basic knowledge regarding what are hooks and why we use them.

What is a custom hook

Custom hooks are functions that provide mechanism to re-use stateful logic such that all the states and effects used within a custom hook remain fully isolated. We can also use other hooks within a custom hook. All custom hooks’ name should start with “use” similar to the other hooks.

Why use a custom hook

  • Allow sharing re-usable logic
  • Does not share data between components
  • Easy to separate complex logic from components

How to build a custom hook

Use case: We have built applications which involve fetching the data from an API. While doing that, we usually display a loading indicator so that user can know that something is in progress and might load soon. If we receive any errors while fetching the data, we display the error toast message.

Implementation: We will create a custom hook named “useFetch” which will make the API calls, as well as manage the loading and error state. This hook can be re-used whenever we want to fetch data using API calls with no need of managing the loading and error states individually everywhere.



#react #react-hook #web-development #javascript #developer

Build a Custom useFetch React Hook
1.60 GEEK