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 };
Enter fullscreen mode
Exit fullscreen mode
}
export default useFetch;
Use the Custom Hook in App.jsx:
import React from "react";
import useFetch from…