T E C h O C E A N H U B

Web storage (localStorage, sessionStorage)

Web storage refers to the web browser’s ability to store data locally on the client-side in a web application. This allows developers to store data on the user’s device and retrieve it later, even after the browser window is closed or the user navigates away from the page. Web storage provides two main mechanisms for data storage: localStorage and sessionStorage.

  1. localStorage: localStorage is a type of web storage that allows you to store key-value pairs persistently on the user’s device. The data stored in localStorage remains available even after the browser is closed and can be accessed by the same web application domain across different sessions. It is typically used to store settings, preferences, or other data that needs to be retained between visits.

To use localStorage in JavaScript, you can set and retrieve data like this:

// Storing data in localStorage
localStorage.setItem('key', 'value');

// Retrieving data from localStorage
const value = localStorage.getItem('key');

// Removing data from localStorage
localStorage.removeItem('key');

// Clearing all data from localStorage
localStorage.clear();
  1. sessionStorage: sessionStorage is similar to localStorage, but with one key difference: the data stored in sessionStorage is only accessible for the duration of the current browser session. Once the user closes the browser or navigates to a different page within the same website, the data is cleared. This makes sessionStorage useful for storing temporary data that should not persist between sessions, such as data needed for a particular transaction or browsing session.

Usage of sessionStorage is quite similar to localStorage:

// Storing data in sessionStorage
sessionStorage.setItem('key', 'value');

// Retrieving data from sessionStorage
const value = sessionStorage.getItem('key');

// Removing data from sessionStorage
sessionStorage.removeItem('key');

// Clearing all data from sessionStorage
sessionStorage.clear();

It’s important to note that both localStorage and sessionStorage have size limitations (usually around 5-10 MB) and are subject to browser security settings, which may prevent access in certain scenarios, such as when browsing in incognito mode or from a restricted origin.

Web storage provides a convenient way to store data on the client-side, reducing the need to make frequent server requests for small pieces of data, and thus improving the overall performance and user experience of web applications.

Copyright ©TechOceanhub All Rights Reserved.