Blog>
Snippets

Implementing Caching Strategies for Deferred Data

Showcase caching strategies for deferred data to avoid redundant network requests, improving app performance and reducing latency.
const cache = {};

function fetchData(url) {
  // Check if data is in cache
  if (cache[url]) {
    console.log('Fetching from cache:', url);
    return Promise.resolve(cache[url]);
  }

  // Fetch data and store it in cache
  console.log('Fetching from network:', url);
  return fetch(url)
    .then(response => response.json())
    .then(data => {
      cache[url] = data; // Store fetched data in cache
      return data;
    });
}
This code demonstrates a simple caching strategy for deferred data fetching. Before fetching data from a network, it checks if the data is already present in a local cache object. If the data is in the cache, it returns the cached data, avoiding a network request. If the data is not in the cache, it performs a network request, caches the received data, and then returns it.
function deferredFetch(url, delay = 1000) {
  // Return a promise that fetches data after a delay
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      fetchData(url) // Use cached fetchData function
        .then(resolve)
        .catch(reject);
    }, delay);
  });
}
This code snippet extends the caching strategy by introducing deferred fetching. Instead of immediately fetching the data, it waits for a specified delay before executing the fetch. This is useful in scenarios where you want to reduce the load on the server or network by delaying non-critical data fetching to a later point in time.