React Custom Hook Fetch and Cache API Response Tutorial

This tutorial will give you an overview of how to create a separate or independent custom hook that fetches and caches api response or data in React js application.

We will also show you how to use a custom hook with the Bootstrap library to display api data in react component.

It could be hard to combine creating and caching api response in React, especially if you are new to react development. So get along and learn how to work with a custom hook, api cache in react js.

React custom hook fetch and cache api data example; Custom hooks are created and used in React to accomplish some programming tasks. API calls are made to fetch data from the servers.

Similarly, caching is used to memoize the value so that we can prevent re-renders in React.

How to Cache API Response using Custom Hook in React Js

  • Step 1: Download React Application
  • Step 2: Add Bootstrap Module
  • Step 3: Build Custom Hook
  • Step 4: Render and Cache Data with Custom Hook
  • Step 5: Run Development Server

Download React Application

Developing React app requires a particular environment; we will install Create React App tool in our development system for building React single-page applications.

npm install create-react-app --global

We have configured the react environment; now we can install a react app using the suggested command:

npx create-react-app react-demo

Let us get into the app folder and start learning to create a custom hook.

cd react-demo

Add Bootstrap Module

This step is completely optional; we are going to install the bootstrap library in react. Bootstrap framework is ideally used for rapid and eloquent web development.

npm install bootstrap

Head over to src/App.js folder, start importing bootstrap CSS path from the node modules folder:

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'

Build Custom Hook

In your react project directory, create the useApiRes.js file. In this file we will write code to retrieve data using api and cache the API response.

import { useReducer, useRef, useEffect } from 'react'

export const useApiRes = (api) => {
  const cacheApi = useRef({})

  const initialState = {
    status: 'idle',
    data: [],
    error: null,
  }

  const [state, dispatch] = useReducer((state, action) => {
    switch (action.type) {
      case 'RENDERING':
        return { ...initialState, status: 'Rendering' }
      case 'RENDERED':
        return { ...initialState, status: 'Rendered', data: action.payload }
      case 'ERROR':
        return { ...initialState, status: 'Error', error: action.payload }
      default:
        return state
    }
  }, initialState)

  useEffect(() => {
    let cancelReq = false
    if (!api || !api.trim()) return

    const getData = async () => {
      dispatch({ type: 'RENDERING' })
      if (cacheApi.current[api]) {
        const data = cacheApi.current[api]
        dispatch({ type: 'RENDERED', payload: data })
      } else {
        try {
          const res = await fetch(api)
          const data = await res.json()
          cacheApi.current[api] = data
          if (cancelReq) return
          dispatch({ type: 'RENDERED', payload: data })
        } catch (error) {
          if (cancelReq) return
          dispatch({ type: 'ERROR', payload: error.message })
        }
      }
    }

    getData()

    return function cleanReq() {
      cancelReq = true
    }
  }, [api])

  return state
}

Render and Cache Data with Custom Hook

We have previously build the custom hook, now time has come to consume the React custom hook. We will show you how to fetch and cache api response at the same time show the users data in React component.

Head over to src/App.js file and place the given code into the file.

import React from 'react'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import { useApiRes } from './useApiRes'

const App = () => {
  const apiUrl = 'https://jsonplaceholder.typicode.com/users'

  const { data, status, error } = useApiRes(apiUrl)

  return (
    <div className="container mt-3">
      <h2 className="mb-3">React Cache API Response Example</h2>

      {
        <ul className="list-group">
          {data.map((user, index) => {
            return (
              <li key={index} className="list-group-item">
                {user.name}
              </li>
            )
          })}
        </ul>
      }
    </div>
  )
}

export default App

Run Development Server

All the code has been written, now its time for you to move to your terminal window. Type the provided command then run the command to serve the app.

npm start

We can serve the app through browser with given url:

http://localhost:3000

React Custom Hook Fetch and Cache API Response Tutorial