React Custom Hook: useFetch
Sergey Leschev
Posted on August 17, 2023
In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useFetch" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.
Github: https://github.com/sergeyleschev/react-custom-hooks
import useAsync from "../useAsync/useAsync"
const DEFAULT_OPTIONS = {
headers: { "Content-Type": "application/json" },
}
export default function useFetch(url, options = {}, dependencies = []) {
return useAsync(() => {
return fetch(url, { ...DEFAULT_OPTIONS, ...options }).then(res => {
if (res.ok) return res.json()
return res.json().then(json => Promise.reject(json))
})
}, dependencies)
}
One of the key advantages of useFetch is its simplicity. By abstracting away the fetch logic into a reusable hook, developers can quickly and effortlessly make HTTP requests and handle responses without repetitive boilerplate code. With just a few lines, useFetch handles the network request, parses the JSON response, and provides the resulting data.
The useFetch hook also offers flexibility through its customizable options parameter. Developers can pass additional headers, query parameters, or request options as needed, ensuring compatibility with various APIs. The hook follows best practices by providing default options for setting the Content-Type header as application/json, promoting clean and consistent code.
Another noteworthy feature of useFetch is its support for dependency tracking. By specifying an array of dependencies, developers can control when the hook triggers a new request. This feature enhances performance optimization, allowing for selective data updates based on changes in the dependency array.
import { useState } from "react"
import useFetch from "./useFetch"
export default function FetchComponent() {
const [id, setId] = useState(1)
const { loading, error, value } = useFetch(
`https://jsonplaceholder.typicode.com/todos/${id}`,
{},
[id]
)
return (
<div>
<div>{id}</div>
<button onClick={() => setId(currentId => currentId + 1)}>
Increment ID
</button>
<div>Loading: {loading.toString()}</div>
<div>{JSON.stringify(error, null, 2)}</div>
<div>{JSON.stringify(value, null, 2)}</div>
</div>
)
}
This versatile hook can be utilized in numerous scenarios. For example, in a React component that needs to fetch and display dynamic data, useFetch simplifies the process. It takes care of handling loading and error states, keeping the component clean and focused on rendering the received data. Additionally, useFetch is particularly useful in scenarios where the fetched data is based on dynamic variables or user interactions, as demonstrated in the FetchComponent example.
Full Version | React Custom Hooks:
https://dev.to/sergeyleschev/supercharge-your-react-projects-with-custom-hooks-pl4
Posted on August 17, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.