DEV Community

Cover image for How To Create A Custom Hooks In React.
Emmanuel Umeh
Emmanuel Umeh

Posted on

How To Create A Custom Hooks In React.

Custom hooks are reusable functions used for stateful logic. A custom Hook is a JavaScript function whose function starts with ”use”.

In this tutorial, we will learn how to "how to create a customhooks in react"

Prerequisite
Before we begin, these are technologies you should be familiar with and have installed on your local machine to follow up these guides:

  1. Nodejs v18+

  2. React Knowledge

In this tutorial, we will build a simple e-commerce store that fetches data from FakeStoreAPI

Let's start by running this in our terminal.

  1. Open your terminal and run
    npx create-react-app reactapp

  2. Navigate to the folder
    cd reactapp

  3. Run
    npm start

Now our app is running locally, let's get started by:

Creating a customhooks folder

Image description

Inside the customhooks folder create a Usefetch.js file and input this code.

import { useState, useEffect } from "react";

 const Usefetch = (url) => {
   const [images, setData] = useState([]);

   useEffect(() => {
     fetch(url)

       .then((res) => res.json())
       .then((images) => setData(images));
   }, [url]);

   return [images];
 };

 export default Usefetch;
Enter fullscreen mode Exit fullscreen mode

Now create a imageHolder.js file and input this code.

 import React from "react";

 const imageHolder = () => {

   return (
     <>
       {
         images.map((item) => {
           return <p key= {item.id}>
              <img src={item.image}/>
             <h4>{item.title}</h4>
             <h1>{item.price}</h1>
             </p>
         })}
     </>
   );

 };

 export default imageHolder;

Enter fullscreen mode Exit fullscreen mode

Now let's import our useFetch custom hooks into our ImageHolder.js file.

 import React from "react";
 import Usefetch from "../customhooks/Usefetch";

 const imageHolder = () => {

   // Fetching images from fakestoreApi
   const [images] = Usefetch("https://fakestoreapi.com/products");

   return (
     <>
       {
         images.map((item) => {
           return <p key= {item.id}>
             <img src={item.image}/>
             <h4>{item.title}</h4>
             <h1>{item.price}</h1>
             </p>
         })}
     </>
   );

 };

 export default imageHolder;

Enter fullscreen mode Exit fullscreen mode

Now let's import the ImageHolder into our App.js file

 import React from "react";
 import ImageHolder from "./ImageHolder";

 function App() {

   return (
     <div className="">
       <ImageHolder />
       </div>

           )

   }
 export default App;

Enter fullscreen mode Exit fullscreen mode

Conclusion
Custom hooks are reusable functions that aid code reusability. I can say this is the best hack ever, react developers should know when creating a large or small project.

Thanks for reading.

Top comments (0)