We have an app with different articles. I want to cache an article when the user has read it, but make sure that I display the latest data. I came up with this hook:

  React.useEffect(() => {
    (async function fetchArticle() {
      const articleURL = `${BASE_URL}/services/node/${route.params.nid}`;
      try {
        const cached = await articleCache.get(route.params.nid);
        if (cached) {

          axios(articleURL).then(({ data }) =>
            articleCache.set(route.params.nid, JSON.stringify(data)),
        } else {
          const { data } = await axios(articleURL);

          await articleCache.set(route.params.nid, JSON.stringify(data));
      } catch (err) {
      } finally {
  }, [route.params.nid]);

Does it make sense to fetch the data again every time? It seems kind of excessive to me, but I can't think of another away without the API being changed and returning some kind of timestamp instead of the full article to reduce the size of the request.

Is this way ok or can it be improved?

  • 1
    Not an answer but an observation: there's a whole layer in the browser that's designed to handle caching requests, including things like if-modified-since so that data does not have to be unnecessarily re-sent, and it's a shame that modern SPA style erases all of that.
    – pjc50
    Commented Apr 28, 2022 at 12:29
  • Well it's a mobile app. I am not sure that applies. But yeah, I am always wondering whether caching works with something like React, and the answer seems to be no :-(
    – Gh05d
    Commented Apr 28, 2022 at 12:37


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.