DEV Community

Cover image for Stop using Redux, cache requests
Omid Nikrah
Omid Nikrah

Posted on

Stop using Redux, cache requests

In this article, I don’t want to talk about the new state management library or compare Redux with Context API. I just want to say, in some situations, you don’t need to Redux and you can handle it by other solutions.

Imagine we have a PWA and it’s an online shop. Usually, we navigate between products and check them. When you like a product, you may check it many times and it has a bad experience if every time you should wait for getting product data from the server. We have two solutions to have a better experience.

One. Using Redux (Not recommended)

We can use Redux and have a state to push the product data in this state. But when you have developed a large scale application, It’s not a good solution.

Two. Cache Requests (Recommended)

CACHE REQUESTS. Why using Redux until you can cache requests?

We can have cache storage to store the requests data and when an API request called, first we looking for the response in the cache storage, and if we don’t have it, now we need to call the API request.

We have many ways to implement this feature and I will show you some of them.

You can implement it as the following:

class CacheRequests {
  constructor() {
    this.caches = new Map();
  }

  set(url, response) {
    this.caches.set(url, response);
  }

  get(url) {
    return this.caches.get(url);
  }

  has(url) {
    return this.caches.has(url);
  }
}

const cache = new CacheRequests();

const Request = (url, options) => {
  if (cache.has(url)) {
    return cache.get(url);
  }
  fetch(url, options).then((response) => {
    console.log(response);
    cache.set(url, response);
  });
}

Or if you are using axios, you can also use axios-extensions or axios-cache-adaptor packages.

Top comments (0)