useFetch is a Custom Hook in React. It is used to fetch data from an API and reuse the fetching logic in multiple components.
useFetch is not a built-in React Hook. We create it ourselves using built-in hooks like useState and useEffect.
Let's fetch user data from an API.
Create useFetch.js:
import { useState, useEffect } from "react";
function useFetch(url) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchData() {
try {
setLoading(true);
const response = await fetch(url);
if (!response.ok) {
throw new Error("Something went wrong");
}
const result = await response.json();
setData(result);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchData();
}, [url]);
return { data, loading, error };
}
export default useFetch;
Use the Custom Hook in App.jsx:
import React from "react";
import useFetch from "./useFetch";
function App() {
const { data, loading, error } =
useFetch("https://jsonplaceholder.typicode.com/users");
if (loading) {
return <h2>Loading...</h2>;
}
if (error) {
return <h2>Error: {error}</h2>;
}
return (
<div>
<h2>User Details</h2>
{data.map((user) => (
<div key={user.id}>
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
))}
</div>
);
}
export default App;
Top comments (0)