DEV Community

loading...
Cover image for What is localStorage?

What is localStorage?

tolentinoel profile image Ellaine Tolentino ・2 min read

I have encountered utilizing localStorage in one of my projects back when I was in coding bootcamp. I knew of its existence when we were taught of using it to persist data for JWT authentication and that is all I knew of it.

Little did I know there is more usage of localStorage than tokens!
Let's take a quick look together and learn a little bit of what is localStorage?

Methods:

Method Function
setItem(key, value). Sets the key-value pair you want to store.
removeItem(name) remove the name-value pair identified by name.
getItem(name) get the value for a given name.
key(index) get the name of the value in the given numeric position.
clear() remove all values.
length to get the number of key-value pairs

The localStorage can store only strings for its values. It automatically converts non-string data into a string before storing it.

An example of that is this:
Retrieving data from localStorage

When you retrieve data from a Storage object, you’ll always get the data as a string. Same with sessionStorage and Cookies. You can also store objects in the localStorage. We would just have to use JSON.stringify() to store the object.

Example:
Storing objects in localStorage
Like as you can see, once stored, the whole object turns into a string even when trying to get the data back. But this data can be converted back to an object by using JSON.parse().

Just like this;
JSON parse

Capacity & Usage

Some say that most modern web browsers allow you to store up to 5MB, while others say it's close to unlimited.

When it comes to storing data, localStorage keeps it until the browser is closed or until you run the localStorage.clear() command.

On my previous project, I used localStorage.clear() when the user logs out of the web app and clears out any token stored in the browser.
Check it out here on our handleLogout function;
handleLogout function

I have also used localStorage in one of my React app projects to manage the theme of the page! Since storing the theme of the app didn't need any security requirement, I tried and stored values in there.

Part of the component that toggles the theme is an onClick eventListener that triggers a switchTheme function that contains an if statement & it looks like this;

switchTheme

See that the main use of the localStorage is to really just store key-value pairs which can be used on many other things.

So that is it! I hope you had fun glancing through this blog about localStorage and hopefully helped you in some way in persisting data other than cookies or state.

Do you have any other experience of using localStorage in a different way? Let me know in the comments below! I would love to try them out!

Discussion (19)

pic
Editor guide
Collapse
christiankozalla profile image
Christian Kozalla

This is an excellent post on how localStorage works and use it to store data beyond simple strings with JSON.parse and JSON.stringify ❤️

With this pattern you can actually use localStorage like an in-browser NoSQL Database

I've exploited this pattern to develop a small Vuejs App allowing a user to store meals and plan which meals to cook the next week

Anyways, I meant to write a post about localStorage, but I think if I write about that app, I will just link back to this post to cover localStorage 😄

Collapse
tolentinoel profile image
Ellaine Tolentino Author

Thank you! I still don’t know much besides the basic functionalities but I would love to know more! I’ll keep an eye if you get to post more about localStorage!

Collapse
ivanjeremic profile image
Ivan Jeremic

Don't use LocalStorage anymore in apps, use IndexedDB

Collapse
christiankozalla profile image
Christian Kozalla

Okay, thanks for the tip.

What are the advantages of indexedDB over localStorage?

Thread Thread
ivanjeremic profile image
Ivan Jeremic

It is not blocking javascript I recommend watching youtu.be/NNuTV-gjlZQ

Thread Thread
christiankozalla profile image
Christian Kozalla

Nice, so thank you for pointing out IndexedDB, since I wasn't familiar with it. One more advantage I have found is, that it can be used with Service Workers (or Web Workers in general) 👍

Collapse
3in0 profile image
3in0

I think localStorage persists until either clear() is called or the browser cache is cleared, so it is available to the page across sessions. However, sessionStorage only lives for the duration of the session.

I've used it to store personal high scores on games. I guess one advantage over cookies is that you aren't sending it back to the server with each request.

Collapse
sudarshansb143 profile image
Sudarshan Sawandkar

But if you designed multiple games and stored the high scores of all in local storage then you call clear().

Then will it clear all high scores or only clear that specific games high score in which you call clear() ?

Collapse
3in0 profile image
3in0

Yes, that would clear all local storage for everything hosted under the same host/port. I guess if you wanted to just clear the data for one page/game you'd just delete or reset the key/value pairs associated with that page rather than use clear().

Thread Thread
tolentinoel profile image
Ellaine Tolentino Author

Oh yes! this is a good thing to point out! Thank you!

Collapse
joelnwalkley profile image
Joel N. Walkley

Thanks! Lots I didn't know here, especially about the limitations. One use I had was for users to see a live version of their edits to a profile before committing them. That way if they wanted to return to edits they could without updating the underlying data.

I've been wondering - what are the limitations of using localStorage as if it were global state in a React app (say for folks who want to avoid Redux)?

Collapse
tolentinoel profile image
Ellaine Tolentino Author

I tried to use locaStorage as a global state on a project, and it doesn’t automatically reflect the updates or changes in state unlike using Redux or there was somewhat of a delay since it needs to getItem then setItem and then return it.

Collapse
lelepg profile image
Leticia Pegoraro Garcez

Congratulations for a awesome post! I was just thinking about this these days, and your article came in perfect timing haha. I was working on a project these days and I was suffering on how to keep variables from a page to other, ans local storage was the way to go!

Collapse
ivanjeremic profile image
Ivan Jeremic

LocalStorage should not be used anymore in production apps, there is indexeddb.

Collapse
raddevus profile image
raddevus

Even if you're saving only one or two name value pair?

localStorage is extremely easy to use and is secure.

Now, you may want to say something like:
"Cookies should not be used anymore in production apps, there is localStorage."

Collapse
ivanjeremic profile image
Ivan Jeremic • Edited

Even then yes, LocalStorage is blocking the main thread, for this I recommend idb-keyval which lets you store small things like you mentioned in indexeddb also watch this video please to learn more youtu.be/NNuTV-gjlZQ

Collapse
zetareticoli profile image
Francesco Improta

Thank you, this post clearify what localStorage is.

Collapse
tolentinoel profile image
Collapse
arvindpdmn profile image
Arvind Padmanabhan

A more general topic is Web Storage, that talks about local storage and session storage. Learn more at devopedia.org/web-storage