Menu

What is useFetch in React?
📰

What is useFetch in React?

DEV Community: frontend·SATHISHKUMAR R·12 days ago
#SuwHXUIP
#devtofrontend#devto#dev#usefetch#error
Reading 0:00
15s threshold

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…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.