useFetch()

Here is a React Hook which aims to retrieve data on a Rest API using the Axios library.

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 Axios option object 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.

Sources:

You can read this article from "Smashing Magazine" which explains how to build a custom react hook to fetch and cache data

The Hook

1import { useEffect, useReducer, useRef } from 'react'
2import axios, { AxiosRequestConfig } from 'axios'
3
4// State & hook output
5interface State<T> {
6 status: 'init' | 'fetching' | 'error' | 'fetched'
7 data?: T
8 error?: string
9}
10
11interface Cache<T> {
12 [url: string]: T
13}
14
15// discriminated union type
16type Action<T> =
17 | { type: 'request' }
18 | { type: 'success'; payload: T }
19 | { type: 'failure'; payload: string }
20
21function useFetch<T = unknown>(
22 url?: string,
23 options?: AxiosRequestConfig,
24): State<T> {
25 const cache = useRef<Cache<T>>({})
26 const cancelRequest = useRef<boolean>(false)
27
28 const initialState: State<T> = {
29 status: 'init',
30 error: undefined,
31 data: undefined,
32 }
33
34 // Keep state logic separated
35 const fetchReducer = (state: State<T>, action: Action<T>): State<T> => {
36 switch (action.type) {
37 case 'request':
38 return { ...initialState, status: 'fetching' }
39 case 'success':
40 return { ...initialState, status: 'fetched', data: action.payload }
41 case 'failure':
42 return { ...initialState, status: 'error', error: action.payload }
43 default:
44 return state
45 }
46 }
47
48 const [state, dispatch] = useReducer(fetchReducer, initialState)
49
50 useEffect(() => {
51 if (!url) {
52 return
53 }
54
55 const fetchData = async () => {
56 dispatch({ type: 'request' })
57
58 if (cache.current[url]) {
59 dispatch({ type: 'success', payload: cache.current[url] })
60 } else {
61 try {
62 const response = await axios(url, options)
63 cache.current[url] = response.data
64
65 if (cancelRequest.current) return
66
67 dispatch({ type: 'success', payload: response.data })
68 } catch (error) {
69 if (cancelRequest.current) return
70
71 dispatch({ type: 'failure', payload: error.message })
72 }
73 }
74 }
75
76 fetchData()
77
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 './useFetch'
4
5interface Post {
6 userId: number
7 id: number
8 title: string
9 body: string
10}
11
12export default function Component() {
13 const url = `http://jsonplaceholder.typicode.com/posts`
14 const { status, data, error } = useFetch<Post[]>(url)
15 console.log({ status, data, error })
16
17 // your component JSX
18 return <div>{status}</div>
19}

Created:
8 months ago