Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache react component fetches?

Let's say you have a component like this:

function MyComponent({ index }) {
  const [data, setData] = useState('');

  useEffect(() => {
    (async function() {
      const result = await fetchData(index);
      setData(result);
    })();
  }, [index]);

  return <h1>{data}</h1>;
}

Whenever the index changes, we will re-fetch the data and render it. How can I cache this so that we don't have to re-fetch the same index from before?

like image 924
Vic Avatar asked Dec 21 '25 10:12

Vic


1 Answers

You want to memoize your results, like:

const cache = {};

async function memoFetch(index) {
  if (cache[index]) {
    return cache[index];
  }
  const data = fetchData(index);
  cache[index] = data;
  return data;
}


function MyComponent({ index }) {
  const [data, setData] = useState('');

  useEffect(() => {
    (async function() {
      const result = await memoFetch(index);
      setData(result);
    })();
  }, [index]);

  return <h1>{data}</h1>;
}

like image 132
moonwave99 Avatar answered Dec 23 '25 00:12

moonwave99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!