Caching data is the process of storing data in a fast, accessible storage layer (the cache) to improve performance and reduce the time needed to retrieve frequently accessed information. Caches can exist in different layers of a system like the disk, memory, or right there in the web browser. We have the client-side caching, server-side caching and CDN-caching. But for the sake of this article, we’ll be dwelling on the client-side caching — local storage.
Prerequisite
- Familiar with basic frontend technologies like CSS and JavaScript.
Getting Started with Local Storage
Local Storage is a simple key-value storage system provided by web browsers. It allows developers to store data efficiently on the client side, which can improve performance. Unlike cookies, Local Storage does not send data to the server with every HTTP request, making it lightweight and efficient for caching data. Its basic syntax includes the following:
localStorage.setItem(key, value)
: Store a key-value pair.localStorage.getItem(key)
: Retrieve a value by its key.localStorage.removeItem(key)
: Remove a specific key-value pair.localStorage.clear()
: Clear all stored data
Below is a simple snippet showing the storing and retrieving of a simple key-value pair -
// Store a value
localStorage.setItem('username', 'Voke');
// Retrieve the value
const username = localStorage.getItem('username');
console.log(username); // Output: "Voke"
// Remove the value
localStorage.removeItem('username');
// Clear all values
localStorage.clear();
But hey! there are times when things don’t get too rosy and there is an actual need to store complex data like an object or array, How do you go about that? Well, first and foremost, you got to have it at the back of your mind that Local Storage can only store strings. To store objects or arrays, you’ll need to convert them to a JSON string with JSON.stringify
. You then retrieve them by parsing the string back into its original format using JSON.parse
. An example is shown below -
// Store an object
const user = { id: 1, name: 'Voke Pop', role: 'admin' };
localStorage.setItem('user', JSON.stringify(user));
// Retrieve the object
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser.name); // Output: "Voke Pop"
Practical Use Cases of Caching Data to Local Storage
Retaining User Preferences: In a scenario where a user has customized their theme, language, or layout preferences already and then the site refreshes - maybe accidentally or not, cached data from local storage will retain these preferences regardless.
Enabling Offline Access: In a scenario where its critical for a weather app to show the last fetched data even when the user is offline, cached data from local storage can come in handy here.
Preventing Redundant Pop-Ups: In a scenario where a website is to show a pop-up (e.g., a subscription prompt) only once per user, cached data in the local storage can be used to track if the pop-up has already been shown.
Saving Form Data: In a scenario where a user fills out a long form or survey but accidentally refreshes or navigates away from the page, inputs cached temporarily in Local storage will help prevent data loss.
Persistent Shopping Cart: An e-commerce site could allow users to add items to their cart without logging in because carted items are cached in local storage. So, they persist even if the user closes and reopens the browser.
Using the context of the first use case given above, let’s dive into how to cache data using local storage.
Retaining User Preferences
Alright, I’ll be creating a blank site for this and we will focus only on the theme aspect of the said preference. Below is a code break-down on how we can achieve that.
HTML code snippet -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blank shii</title>
<style>
body{
padding: 1rem;
padding-top: 3.5rem;
background-color: hsl(222, 26%, 31%);
}...
....
...
/* Style the rest to taste*/
</style>
</head>
<body>
<section id="switch">
<label class="toggle" onclick="changetheme()">
<span class="slider" ></span>
<span id="ball"></span>
</label>
</section>
<script src="index.js"></script>
</body>
</html>
JavaScript code snippet -
const toggle = document.querySelector('.toggle');
const body = document.querySelector('body');
const slider = document.querySelector('.slider');
const ball = document.querySelector('#ball');
// change theme on toggle
function changetheme() {
if (body.classList.contains("default")) {
ball.style.transform = 'translateX(25px)';
body.classList.remove("default");
body.classList.add("light");
localStorage.setItem('theme', 'light');
} else if (body.classList.contains("light")) {
ball.style.transform = 'translateX(55px)';
body.classList.remove("light");
body.classList.add("purple");
localStorage.setItem('theme', 'purple');
} else {
ball.style.transform = 'translateX(0px)';
body.classList.remove("purple");
body.classList.add("default");
localStorage.setItem('theme', 'default');
}
}
function restoreTheme() {
const storedTheme = localStorage.getItem('theme');
if (storedTheme === "light") {
body.classList.add("light");
body.classList.remove("default")
ball.style.transform = 'translateX(25px)';
}
if (storedTheme === "purple") {
body.classList.add("purple");
body.classList.remove("default")
ball.style.transform = 'translateX(55px)';
}
}
restoreTheme();
As you can see above, with each toggle, I update the theme value in the localStorage
while I retrieve the value in the restoreTheme()
function.
Alright, this is what you get before caching to local storage - the theme gets back to default when the browser is refreshed
And this is the final result after caching to local storage - the theme remains the same.
Conclusion
While caching data to local storage can help provide a seamless and personalized interaction by remembering settings like themes or languages, it is advisable to keep data at a minimum. Avoid storing large datasets; use it for lightweight information. So go ahead and try implementing Local Storage in your own projects to see its potential in action. This simple feature can significantly improve the usability of your web applications.