useFetch()

Here is a React Hook which aims to retrieve data on an API using the native Fetch API.

I used a reducer to separate state logic and simplify testing via functional style.

The received data is saved (cached) in the application via useRef, but you can use LocalStorage (see useLocalStorage()) or a caching solution to persist the data.

The fetch is executed when the component is mounted and if the url changes. If ever the url is undefined, or if the component is unmounted before the data is recovered, the fetch will not be called.

This hook also takes the request config as a second parameter in order to be able to pass the authorization token in the header of the request, for example. Be careful though, the latter does not trigger a re-rendering in case of modification, go through the url params to dynamically change the request.

Side notes:

  • To understand how is working this hook, you can read this article from "Smashing Magazine" which explains how to build a custom react hook to fetch and cache data
  • For usage in SSR, consider using window.fetch.polyfill
  • It's a very simple fetch hook for basic use cases and learning purposes. For advanced usages and optimisations, see these other hooks more powerfull like useSWR, useQuery or if you're using Redux Toolkit, consider RTK Query.

The Hook

1import { useEffect, useReducer, useRef } from 'react'
2
3interface State<T> {
4 data?: T
5 error?: Error
6}
7
8type Cache<T> = { [url: string]: T }
9
10// discriminated union type
11type Action<T> =
12 | { type: 'loading' }
13 | { type: 'fetched'; payload: T }
14 | { type: 'error'; payload: Error }
15
16function useFetch<T = unknown>(url?: string, options?: RequestInit): State<T> {
17 const cache = useRef<Cache<T>>({})
18
19 // Used to prevent state update if the component is unmounted
20 const cancelRequest = useRef<boolean>(false)
21
22 const initialState: State<T> = {
23 error: undefined,
24 data: undefined,
25 }
26
27 // Keep state logic separated
28 const fetchReducer = (state: State<T>, action: Action<T>): State<T> => {
29 switch (action.type) {
30 case 'loading':
31 return { ...initialState }
32 case 'fetched':
33 return { ...initialState, data: action.payload }
34 case 'error':
35 return { ...initialState, error: action.payload }
36 default:
37 return state
38 }
39 }
40
41 const [state, dispatch] = useReducer(fetchReducer, initialState)
42
43 useEffect(() => {
44 // Do nothing if the url is not given
45 if (!url) return
46
47 const fetchData = async () => {
48 dispatch({ type: 'loading' })
49
50 // If a cache exists for this url, return it
51 if (cache.current[url]) {
52 dispatch({ type: 'fetched', payload: cache.current[url] })
53 return
54 }
55
56 try {
57 const response = await fetch(url, options)
58 if (!response.ok) {
59 throw new Error(response.statusText)
60 }
61
62 const data = (await response.json()) as T
63 cache.current[url] = data
64 if (cancelRequest.current) return
65
66 dispatch({ type: 'fetched', payload: data })
67 } catch (error) {
68 if (cancelRequest.current) return
69
70 dispatch({ type: 'error', payload: error as Error })
71 }
72 }
73
74 void fetchData()
75
76 // Use the cleanup function for avoiding a possibly...
77 // ...state update after the component was unmounted
78 return () => {
79 cancelRequest.current = true
80 }
81 // eslint-disable-next-line react-hooks/exhaustive-deps
82 }, [url])
83
84 return state
85}
86
87export default useFetch

Usage

1import React from 'react'
2
3import { useFetch } from 'usehooks-ts'
4
5const url = `http://jsonplaceholder.typicode.com/posts`
6
7interface Post {
8 userId: number
9 id: number
10 title: string
11 body: string
12}
13
14export default function Component() {
15 const { data, error } = useFetch<Post[]>(url)
16
17 if (error) return <p>There is an error.</p>
18 if (!data) return <p>Loading...</p>
19 return <p>{data[0].title}</p>
20}

See a way to make this page better?
Edit there »