Home > database >  Is this mapping in React cached? If so, how does it work?
Is this mapping in React cached? If so, how does it work?

Time:03-18

I have this example react.js code:

const cache = new Map();
const retrieveData = (fileName, data) = {
    const data = cache.get(fileName);
    if (data === undefined) {
        data = someDataRetrievingFunction();
        cache.set(fileName, data);
        return data;
    }
    return data;
}

function Ref({fileName}) {
    return <div>{retrieveData(fileName)}</div>;
}

This code executes everytime a post is clicked and a different fileName is given. If a user were to click a post, exit, then click the same post, would the mapping cache the data that was fetched the first time? Thanks in advance!

CodePudding user response:

If consider this code as is, so const cache = new Map(); is in the root of the file, i.e.

  // posts.js
  import React from 'react'

  const cache = new Map();

  // Other code

cache is singleton and it will not be reset during whole app live. And answer to your question is yes, mapping will cache the data.

But such code is not a good practice. Consider if posts.js will be used in several places of the app. In this case cache will contain previously cached data and this may create problems. For example user may expect cache to be updated, but it will never be updated until browser will be refreshed. Another drawback is that Ref will not be rerendered on cache update. So page may looks buggy.

Another approach is to put cache inside Ref component, like below

function Ref({fileName}) {
    const [cache, setCache] = React.useState({});
    React.useEffect(() = {
      let data = cache[fileName];
      if (data === undefined) {
          data = someDataRetrievingFunction();
          setCache(prevCache => {
            ...prevCache,
            [fileName]: data
          });
      }
    }, [fileName])

    return <div>{cache[fileName]}</div>;
}

In this way, cache will be stable when component is mounted. When component Ref is unmounted, cache will be flushed and on the next mount cache will be recreated.

Another option may be to put cache in redux if it can be used in several places of the app.

CodePudding user response:

No, the code in the render function is run every time the component is rendered (so also at every state change). You should probably use a dedicated library like React Query which will handle the caching for you.

  • Related