One of the most common React Hooks that I’ve found myself using is one to handle API calls. Often we see ourselves writing almost the same codes in more than one different component. Ideally what we could do in such cases would be to extract that recurrent logic into a reusable piece of code (hook) and reuse it where the need be.
I am going to use Fetch API for the HTTP calls. You can use axios as well, it's up to you.
Here is another must feature for our custom hook. We’ll define 2 states, one is a boolean value that indicates whether has an error or not and another one is a string value that includes the error message.
We’ll be also using the try/catch syntax to set and handle error boundaries. It would look like this:
What about parameters? And what about changing it dynamically to use it like filtering or something else? Sounds great. Let's implement this too.
We’ll take parameters as a prop which will be an object. And then, we’ll transpile them with encodeURIComponent to use properly. Following that, we’ll add params state to the dependency of the useEffect hook to trigger it again. It would look like this:
Another common thing I’ve needed is the ability to manually trigger the API call again. A good example would be a page with a list of resources and wanting to refresh the list from a callback after creating a new resource.
To do this we’ll simply keep a number in the state that’s dependent on the useEffect, that we increment every time we want to force a refresh.