🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)
🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)

🔧 Programmierung 🕛 kürzlich 6 Min Lesezeit
0

Using Caching in React with useGetProducts: Improve Performance and UX

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

In this blog post, we'll walk through how to implement a React hook that retrieves data with a cache-first approach, fetching data from a backend only when necessary. The goal is to demonstrate how caching can improve the user experience (UX) by reducing latency and making the app feel faster.



We'll be using a utility function to interact with the cache stored in IndexedDB and demonstrate the process of fetching product data from an API with high latency. This approach reduces the waiting time for users by showing cached data immediately and refreshing the data in the background.






The Problem: High Latency API Calls



Imagine you're building an app that fetches product data from an API. In real-world scenarios, this data may come from a remote server with latency (e.g., 2-3 seconds delay). While waiting for the data, users may feel frustrated. So, how do we solve this problem?



By caching the data using IndexedDB, we can immediately display previously fetched data to users, even while new data is being fetched in the background. This gives users a faster and smoother experience.






Step-by-Step Breakdown of useGetProducts



Let's break down the useGetProducts hook that handles the cache logic and API calls.






Step 1: Define the Product Interface



First, we define the Product interface to represent the data we are working with:




CODE
interface Product {
id: number
name: string
}






This is a simple object structure with id and name representing a product.






Step 2: Simulate an API Call with Latency



Next, we simulate an API call using the getProducts function, which has a built-in delay of 2 seconds to mimic a real backend API with high latency:




CODE
const getProducts = async (): Promise<Product[]> => {
return await new Promise<Product[]>((resolve) =>
setTimeout(
() =>
resolve([
{ id: 1, name: 'Product A' },
{ id: 2, name: 'Product B' },
]),
2000
)
)
}







This function simulates a delayed API call that returns an array of products after 2 seconds.






Step 3: The useGetProducts Hook



Now, let's build the useGetProducts hook. The core idea is that we check if there's cached data available first and use it immediately, then fetch fresh data in the background.




CODE
const useGetProducts = (): {
data: Product[] | undefined
loading: boolean
} => {
const [products, setProducts] = React.useState<Product[] | undefined>(
undefined
)
const [loading, setLoading] = React.useState(true)
const cacheKey = 'cache_products'

// Load products from cache, then fetch from API to update if cache is used.
const loadProducts = React.useCallback(async () => {
setLoading(true)

// Step 1: Load from cache, if available, for immediate display
const cachedProducts = await getCachedData<Product[]>(cacheKey)
if (cachedProducts && cachedProducts.length > 0) {
setProducts(cachedProducts) // Display cached data immediately
setLoading(false)
}

// Step 2: Fetch updated data from API, even if cache was used
try {
const response = await getProducts()
setProducts(response) // Update with fresh data
updateCache(response, cacheKey) // Update the cache with new data
} catch (err) {
console.error('Error fetching products:', err)
} finally {
setLoading(false)
}
}, [])

React.useEffect(() => {
loadProducts()
}, [loadProducts])

return { data: products, loading }
}










Explanation:




  1. State Management: We use React.useState to manage two pieces of state:


  2. products: The array of product data.

  3. loading: A flag to indicate whether the data is still being fetched.


  4. Cache Lookup: In the loadProducts function, we first try to fetch the product data from the cache using the getCachedData function. If cache data exists, it will be shown immediately, and loading will be set to false.


  5. API Call: Simultaneously, we make an API call to fetch fresh data using the getProducts function. Once the new data is fetched, we update the state and cache it for future use using the updateCache function.


  6. Optimistic UI: This approach helps improve the UX because it shows cached data right away, while fresh data is loaded in the background, reducing perceived latency.







Step 4: Caching Utility Functions



The caching is powered by two utility functions, getCachedData and updateCache, which interact with IndexedDB to store and retrieve data.




  • getCachedData: This function retrieves the cached data from IndexedDB.


  • updateCache: This function stores the fresh data in IndexedDB to be used for future requests.




By using IndexedDB, we ensure that data persists even if the user reloads the page or navigates away.




CODE
import {
deleteFromIndexedDB,
getAllKeysFromIndexedDB,
getFromIndexedDB,
saveToIndexedDB,
} from '../indexDb'

const encryptData = (data: string): string => btoa(encodeURIComponent(data))
const decryptData = (encryptedData: string): string =>
decodeURIComponent(atob(encryptedData))

export const updateCache = async <T>(data: T, cacheKey: string) => {
try {
const [, cacheConst] = cacheKey.split('_')

const allKeys = await getAllKeysFromIndexedDB()

const existingKey = allKeys.find((key) => key.endsWith(`_${cacheConst}`))
if (existingKey) {
await deleteFromIndexedDB(existingKey)
}

const serializedData = JSON.stringify(data)
const encryptedData = encryptData(serializedData)
await saveToIndexedDB(cacheKey, encryptedData)
} catch (error) {
console.error('Failed to update cache:', error)
}
}

export const getCachedData = async <T>(cacheKey: string): Promise<T | null> => {
try {
const cached = await getFromIndexedDB(cacheKey)
if (cached) {
const decryptedData = decryptData(cached)
return JSON.parse(decryptedData) as T
}
return null
} catch (error) {
console.error('Failed to retrieve cached data:', error)
return null
}
}







These functions allow us to easily access and update the cache using IndexedDB in the browser, providing persistent data storage.






Step 5: Final Usage



Here's how you would use the useGetProducts hook in a component to display the products:




CODE
import React from 'react'
import useGetProducts from './useGetProducts'

const ProductList: React.FC = () => {
const { data: products, loading } = useGetProducts()

if (loading && !products) return <div>Loading products...</div>
if (!products || products.length === 0) return <div>No products found.</div>

return (
<div>
<h3>Available Products:</h3>
<ul>
{products.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
)
}

export default ProductList










Conclusion



By implementing caching with IndexedDB in this way, we can significantly improve the UX of applications that rely on external APIs with high latency. The user will see cached data immediately, and the fresh data will update behind the scenes, ensuring that users always get the most up-to-date information without the wait.



This approach reduces the perceived latency of your application, making it feel faster and more responsive, even in situations where the backend might be slow.

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
3 Quellen
GPT-6 Astra Release Today? OpenAI’s Next Major AI Model Is Almost Here
1 Quelle
Apple accuses OpenAI of destroying evidence as trade-secrets fight intensifies
1 Quelle
Major AI platforms go down in unprecedented simultaneous outage
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Using Caching in React with useGetProducts: Improve Performance and UX

Thematisch verwandte Begriffe: Using, Caching, React, with · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...