useFetch and Custom React Hooks
First Things First
Released with React 16.8, React Hooks changed the way we see components. They made using React class components unnecessary. Reducing the importance of class-based components came with a tradeoff, however. If you're creating class-based components, you can’t add lifecycle events — so what's the point of using React in the first place?
Here’s where React Hooks come to the rescue. Hooks puts your functions on steroids. You can stop relying on classes and move on to functions (if you prefer classes over functions it’s a different story). Hooks will revolutionize how the React code is written. Sooner or later, you’ll have to dive into them.
Just to reiterate, Hooks are just functions, so one good approach to avoid repeating code, and applying the DRY pattern (if you don’t know what DRY is I would recommend you to read my article about clean code), is to create custom Hooks and import all the components that are necessary to reuse it.
Do Your Homework
If you caring more about productivity than learning, look at the npm packages and see whether there’s already a custom Hook that matches your needs. However, my recommendation is that even if there’s a custom Hook out there for you, you should develop the skills to create your own.
Rules of Hooks
According to the Official React website, there are some rules that we need to follow to use React Hooks:
- Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
The useFetch Hook Purpose
There are many ways to make HTTP REQUEST in the front end, the most common is Axios and fetch. The purpose of this custom Hook is to encapsulate your request and avoid code repetition inside your project:
This code above is the custom Hook, but how do we can use it in reality? It's quite simple:
What's the Advantage of useFetch?
With Hooks, you can access your data layer from the view (your functional component), creating a more reliable structure separating those concepts. This is more important when you need to handle multiple requests inside your functional component. When you need only fetch data once, without pagination or parameters or query parameter updates inside the URL, then
useFetch tends to be not so useful.