More Refactoring with Custom Hook
In the previous sections, we learned how to use hooks to fetch data in a function component. We also discussed how to avoid the infinite loop by specifying the second argument in useEffect
.
In this section, we will learn how to further refactor the previous code by using a custom hook. While developing React applications, it is always a good idea to reuse code in one place and share it across different components.
As we discussed in the previous chapter, and also specified in the React documentation (https://packt.live/3cwLUjN), Building your own hooks lets you extract component logic into reusable functions, which means hooks allow us to easily share and reuse code.
Let's recap how to create the custom hook. To create a custom hook, we first create a new file. The filename convention is to start with use, followed by the hook name—for example, useResponse.js
.
Inside the hook file, we need to import necessary hooks, such as...