loading

Custom Hooks


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.


Build a Hook

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:

Example:

index.js:

------- Example MUKAVA ------

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.

Example:

useFetch.js:

------- Example MUKAVA ------

index.js:

------- Example MUKAVA ------

Example Explained

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.

Share this Doc

Custom Hooks

Or copy link

Explore Topic