useFetch
Here's an example of a custom hook that uses the useEffect
Hook to fetch data from an API:
import { useState, useEffect } from 'react'
function useFetch(url) {
const [data, setData] = useState(null)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(url)
const json = await response.json()
setData(json)
} catch (err) {
setError(err)
} finally {
setIsLoading(false)
}
}
fetchData()
}, [url])
return { data, isLoading, error }
}
This custom hook takes a URL as a parameter and returns an object with three properties:
data
: The JSON data returned from the API.isLoading
: A boolean indicating whether the data is currently being loaded.error
: An error object, if an error occurred while fetching the data.
The useEffect
Hook is used to fetch the data from the API. We use async/await
syntax to make the API call and update the data
state variable when the data is fetched successfully. If an error occurs, we set the error
state variable. Finally, we set the isLoading
state variable to false
to indicate that the data has finished loading.
To use this custom hook, you would simply call it in your functional component and pass in the URL of the API you want to fetch data from:
function MyComponent() {
const { data, isLoading, error } = useFetch('https://api.example.com/data')
if (isLoading) {
return <div>Loading...</div>
}
if (error) {
return <div>Error: {error.message}</div>
}
return (
<div>
{data.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</div>
)
}
In this example, we call the useFetch
hook with the URL of an imaginary API (https://api.example.com/data
). We then use the isLoading
and error
variables to conditionally render a loading spinner or an error message. Finally, we display the data
by mapping over it and rendering each item's name
property.