Return to site

REACT: Custom hook

December 4, 2022

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.

Use the JSONPlaceholder service to fetch fake "todo" items and display the titles on the page:

 

The fetch logic may be needed in other components as well, so we will extract โ›๏ธ that into a custom Hook ๐Ÿช.

Move ๐Ÿ›ป the fetch logic to a new ๐Ÿ†• file to be used as a custom Hook:

 

 

Example Explained

We have created a new ๐Ÿ†• file called useFetch.js containing a function called useFetch which contains ๐Ÿ“ฆ all of the logic needed to fetch our data.

We removed โŒ the hard-coded URL and replaced it with a URL variable that can be passed to the custom Hook๐Ÿช.

Lastly, we are returning ๐Ÿ“ฅ our data from our Hook.

In index.js, we are importing ๐Ÿšš our useFetch Hook and utilizing it like any other Hook. This is where we pass in the URL to fetch data.

Now we can reuse ๐Ÿ”„๏ธ this custom Hook in any component to fetch data from any URL.