Hooks are reusable functions.
When you have component logic that needs to be used by multiple components, we can extract that logic to a custom Hook.
Custom Hooks start with “use”. Example: useFetch.
In the following code, we are fetching data in our Home component and displaying it.
We will use the JSONPlaceholder service to fetch fake data. This service is great for testing applications when there is no existing data.
To learn more, check out the JavaScript Fetch API section.
Use the JSONPlaceholder service to fetch fake “todo” items and display the titles on the page:
index.js:
The fetch logic may be required in other components as well, therefore we will separate it into a new Hook.
Move the fetch logic to a new file that will be used as a custom Hook.
useFetch.js:
index.js:
We’ve made a new file named useFetch.js with a method called useFetch that contains all of the logic required to fetch our data.
We replaced the hard-coded URL with a url variable that may be supplied to the custom hook.
Finally, we return the data from our Hook.
In index.js, we import our useFetch Hook and use it just like any other Hook. This is where we enter the URL to retrieve data from.
We can now use this custom Hook in any component to retrieve data from any URL.
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.