React: Custom Hooks
Custom hooks are reusable functions. They are used when multiple components are going to be using the same logic; That logic is then placed in a custom hook that can be used in those components as many times as necessary. Custom hooks allow for DRY code, and a lean component.
I will display what a fetch request in a functional component looks like.
What is happening above is a regular fetch request using hooks. Compared to a fetch request in class component, this is a pretty lean component. But it is possible to make this component even more lean, and in addition, we can make this fetch request reusable in other components if necessary.
So I created a new file. Like usual, I am importing useState and useEffect from react. Next, I defined a function called useFetch
and passed url
as an argument; by convention, custom hooks are named with “use” in the beginning. I am initializing and setting data with the useState hook. I then make my fetch request within the useEffect hook. I pass the url
is passed in as the fetch argument, and it followed by the then methods. As the second argument in useEffect, I am using url
in array brackets, so the fetch will not happen on a continuous loop. Lastly, I am returning data.
I am back in my component that I am making my fetch request in. As you can see, I am no longer importing useState and useEffect from react. Instead I am importing my custom hook into my component. I am using useFetch
and passing the URL into the hook.