JavaScript : local storage/Session storage

ยท

2 min read

Whether you're preparing for a front-end interview or looking to enhance your web development knowledge, understanding localStorage and sessionStorage is essential. ๐Ÿ“๐Ÿ˜‰

Your web app normally would use memory storage to keep its state from page to page (for example, using useState in React).

The data is temporary and is cleared once the page is unmounted. ๐Ÿ”Œ

But there are some scenarios where you want some data to be persisted between sessions or even browser restarts.

The Web Storage API gives you the ability to store data on the client's side and persist it even if you refresh the page. The data is stored in JSON format.

๐Ÿ“€ localStorage: Data persists even after the browser is closed and reopened. There is no expiration time for the data stored in it. It is only cleared if removed by the web app or the user.

Example: user's preferences like light/dark mode, "remember me" option when logging.

๐Ÿ’ฟ sessionStorage: The session lasts as long as the tab or browser is open and survives page reloads and restores. Each tab or window with the same URL creates its own sessionStorage.

Example: allows the user to refresh without losing some state.

โš  Warning! โš 

Be very careful of what data you store on localStorage/sessionStorage. Avoid storing sensitive or private data. Also, it is not recommended to store authorization tokens there โŒ

Now that you're equipped with the knowledge of localStorage and sessionStorage, you're ready to level up your web development skills!

ย