DEV Community

Nikita Petrochenko
Nikita Petrochenko

Posted on

The importance of cashing ๐Ÿ’ฅ

Alright, let's break it down!

๐Ÿ’ฅ Caching is like stuffing your damn fridge with leftovers ๐Ÿ• so you don't have to hit up the store every time youโ€™re hungry ๐Ÿƒโ€โ™‚๏ธ๐Ÿ’จ. When your server has to serve the same info a hundred times over, instead of working it to death, we slap that data into cache storage. Boomโ€”your site loads faster, and you're the hero of the day ๐Ÿš€๐Ÿ˜Ž

Now, how the hell do we pull this off in code? ๐Ÿ’ป Say youโ€™re using React, and youโ€™ve got some user data you want to keep handy without spamming the API every time. Hereโ€™s how you set it up with a simple cache:

const fetchUserData = async () => {
  if (localStorage.getItem('userData')) {
    return JSON.parse(localStorage.getItem('userData'));
  } 
  const response = await fetch('/api/user');
  const data = await response.json();
  localStorage.setItem('userData', JSON.stringify(data));
  return data;
};
Enter fullscreen mode Exit fullscreen mode

And hereโ€™s the kickerโ€”cache has to stay fresh ๐Ÿ•‘๐Ÿ’จ. You donโ€™t want outdated junk piling up. Use a timer with setTimeout or Cache-Control headers so it auto-clears and refreshes. Keeps your server breathing, and your users arenโ€™t stuck in the stone age ๐Ÿ”ฅ๐Ÿ’ผ

Happy codding โค

Top comments (0)