How to cache API data in React

Caching API data prevents redundant network requests, improves application performance, and provides better user experience during navigation. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented data caching strategies in React applications throughout my 11 years of framework development. The most effective approach is creating a custom hook that stores responses in memory using a Map or localStorage for persistent caching. This method provides automatic cache management with minimal code changes in your components.

Create a custom hook with an in-memory cache using Map to store API responses.

import { useState, useEffect } from 'react'

const cache = new Map()

const useCachedFetch = (url) => {
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (cache.has(url)) {
      setData(cache.get(url))
      setLoading(false)
      return
    }

    fetch(url)
      .then(res => res.json())
      .then(result => {
        cache.set(url, result)
        setData(result)
        setLoading(false)
      })
  }, [url])

  return { data, loading }
}

Here the hook checks if the URL exists in the cache Map before making a network request. If cached data exists, it’s returned immediately without fetching. Otherwise, the data is fetched, stored in the cache, and returned. The cache persists across component re-renders and remounts, eliminating duplicate requests for the same URL.

Best Practice Note:

This is the same caching pattern we use in CoreUI data-driven components for reference data and configurations. Consider implementing cache expiration with timestamps, use SWR or React Query libraries for advanced caching strategies, and clear the cache when data needs to be refreshed.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team