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?
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>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With