Step-by-Step Guide: Creating a Custom Hook in React
Table of Contents
- π§βπ» What Are Custom Hooks?
- π Example: The
useFetch
Hook - β‘ Step 1: Set Up a React Project
- π οΈ Step 2: Add the Custom Hook
- π₯οΈ Step 3: Use the Hook in a Component
- π Step 4: Run the Application
What Are Custom Hooks? π§βπ»
Custom Hooks are JavaScript functions in React that start with use
. They allow you to encapsulate logic or functionality for reuse across multiple components, reducing code duplication and improving maintainability.
In this tutorial, weβll create a custom hook called useFetch
that simplifies dynamic API data fetching.
Example: The useFetch
Hook π
The useFetch
hook is designed to:
- Fetch data from a given API URL.
- Handle loading states.
- Handle errors during the request.
Step 1: Set Up a React Project β‘
If you donβt already have a React project, create one by running the following commands:
npx create-react-app my-app
cd my-app
This will set up a new React project in the my-app
folder.
Step 2: Add the Custom Hook π οΈ
- Inside the
src
directory of your project, create a folder namedhooks
:src/hooks/
- Inside the
hooks
folder, create a file nameduseFetch.js
and add the following code:
import { useState, useEffect } from "react";
export const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (!response.ok) throw new Error("Failed to fetch data");
const result = await response.json();
setData(result);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
};
Step 3: Use the Hook in a Component π₯οΈ
- Create a new component,
DataDisplay.js
, in thesrc
directory. - Add the following code to
DataDisplay.js
:
import React from "react";
import { useFetch } from "./hooks/useFetch";
const DataDisplay = () => {
const { data, loading, error } = useFetch(
"https://jsonplaceholder.typicode.com/posts"
);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<h1>Posts:</h1>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
export default DataDisplay;
Step 4: Run the Application π
- Start the development server:
npm start
- Open your browser and navigate to
http://localhost:3000
. TheDataDisplay
component should display a list of posts fetched from the API.
With these steps, you've successfully created and used a reusable custom hook in React! π