hero

Using LocalStorage in JavaScript

- 5 min read

Intro

In this post, we will explore how to use localStorage in localStorage to store data persistently in the browser. localStorage is a simple but powerful API that allows you to store and retrieve key-value data locally in the user's browser.

What is localStorage?

localStorage is a key-value data storage mechanism that is available in most modern web browsers. Unlike cookies, the data stored in `localStorage` is not sent to the server with each HTTP request, making it an excellent option for storing information locally in the user's browser.

Basic usage of localStorage

You can store data in localStorage using the setItem(key, value)method. Here is an example:

// Storing a data in localStorage
localStorage.setItem("user", "john_doe");

// Fetching stored data
const user = localStorage.getItem("user");
console.log(user); // It will print 'john_doe'

// Deleting data
localStorage.removeItem("user");

Practical example

Suppose we want to remember the user's topic preference:

// Get the stored theme preference
const themePreferred = localStorage.getItem("theme");

// Apply the preferred theme when loading the page.
document.body.classList.add(themePreferred);

Considerations & Conclusion

  • - Data stored in localStorage persists even after closing and reopening the browser.
  • - The maximum allowed size of data in localStorage is variable depending on the browser, but is generally at least 5 MB.

I hope this post has helped you understand how to use localStorage in JavaScript to improve the user experience in your web application!.