DEV Community

Cover image for Using the Local Storage
Sarah Chima
Sarah Chima

Posted on

Using the Local Storage

This article discusses what the local storage is and JavaScript methods that we can use to manipulate it.

I have always known about the local storage but I never got to use it on any project. So I decided to build a note app because I want to be able to use the local storage to store and manipulate data. I decided to share what I learnt while using it. First, let us understand what the local storage is.

What is Local Storage?

Local storage is a web storage object that is available in a user's browser. It allows JavaScript browsers store and access data right in the browser. Basic CRUD operations (create, read, update and delete) can be done on data in the local storage. Data stored in the local storage persists even when the browser window has been closed.

Another form of web storage is Session Storage. This is similar to local storage. The difference is that the data stored in the session storage gets cleared after the session ends, ie. the browser window is closed.

Local Storage Methods

Local Storage methods are the methods that help you manipulate the local storage. That is to save and access data stored in the local storage. These methods include:

  1. setItem()
  2. getItem()
  3. removeItem()
  4. clear()

Let us discuss each of them.

setItem()

We use this method to add new data items to the local storage object or update existing values if the data exists. It takes two arguments, the key of the item to create or update and the value to store. For example, if we want to store a name in the local storage, here is what we will do

    localStorage.setItem('name', 'Sarah');
Enter fullscreen mode Exit fullscreen mode

In the example above, name is the key and Sarah is the value.

This is a simple example. What if you want to store something a little more complex like an array or an object in the local storage? For example, store the notes of the note app in the local storage. It is important to note that local storage stores values as strings. We need to convert the arrays or objects to strings before passing it to the local storage.

We can use the JSON.stringify() method to convert an object or array to strings before passing it the setItem() method.

    const notes = [
        {  
            title: 'A note',
            text: 'First Note'
        },
        {
            title: 'Another note',
            text: 'Second Note'
        }
    ]

    localStorage.setItem('notes', JSON.stringify(notes))
Enter fullscreen mode Exit fullscreen mode

getItem()

This method is used to access data stored in the local storage. It accepts one argument: the key of the item you want to get the value of. It returns the value as a string.

Let us get the name we stored in the local storage.

    const name = localStorage.getItem('name');
    console.log(name) // 'Sarah'
Enter fullscreen mode Exit fullscreen mode

What if we want to get the notes we stored in the local storage? we do the same thing, pass the key to the getItem method. However, to get our value as array, we need to parse it. Otherwise, it returns strings.

    JSON.parse(localStorage.getItem('notes'))
Enter fullscreen mode Exit fullscreen mode

removeItem()

The removeItem() method removes data from the local storage. It receives a key and removes the data item stored with that key from the local storage. If that key does not exist in the local storage, it does nothing.

    localStorage.removeItem('name')

    console.log(localStorage.getItem('name')) //null
Enter fullscreen mode Exit fullscreen mode

clear()

The clear() method clears the entire local storage of all data stored in it. It does not receive any argument.

    localStorage.clear()
Enter fullscreen mode Exit fullscreen mode

Those are the methods available to store and retrieve data from the local storage. Next, let us see how we can listen to storage change events.

Event Listener for Storage Change

To listen to changes in the local storage, we add an event listener for storage.

    // When local storage changes, execute the doSomething function
    window.addEventListener('storage', doSomething())
Enter fullscreen mode Exit fullscreen mode

The storage event fires when either the local storage or the session has been modified in the context of another document. This means that the storage event is not fired on the page that is making changes to the local storage. Rather it is fired in another tab or window if the same page is open there. The assumption is that your page already knows all changes that happen on it. That it will only need notification if the change happens on another page.

I encountered this challenge when building the note app. I was trying to update the part that displays the notes based on changes in the local storage. However, I noticed that when I add a new note, it does not update the notes. Rather it updates the same page opened in another tab. To solve this, I used a state object. After storing to the local storage, I stored or updated a new note in this state. The display of the notes depends on the changes to the state.

Important Things to Note about the Local Storage

One last thing before we go, there are important things about the local storage that we should know.

  1. The local storage is limited to 5MB across all major browsers.
  2. It can easily be accessed from the browser so it should not be used to store any sensitive data or user information.
  3. Operations on the local storage are synchronous. Therefore, they are executed one after another.

Want to see the note app I built? Here's a link to the live app and a link to Github. Have any question on any part of this article or the app, feel free to ask.

You can follow me on Instagram where I post regularly on my tech journey. I also share short notes on things I have learnt.

Top comments (28)

Collapse
 
nikolicstjepan profile image
Nikolić Stjepan

So if I got this right - localStorage is a like cookies except expire part (ls lasts until cleared) and you can store more data in it?

Thanks for the article, it is super useful!

p.s. I relay like design of your Note App!

Collapse
 
marcel_cremer profile image
Marcel Cremer

No it's not - especially not in terms of security (because LocalStorage has no security model).

See also Please Stop Using Local Storage which shows some of the downsides.

Collapse
 
sarah_chima profile image
Sarah Chima

Thanks for reading. I guess your question has been answered by Marcel and Lars.

Collapse
 
larsklopstra profile image
Lars Klopstra ⚡

It's also limited to the client for the specified site, servers and other sites can not access it

Collapse
 
ybogomolov profile image
Yuriy Bogomolov

Sorry, but this article could be a bit misleading to newbie devs. It doesn't describe that accessing localStorage could result in a SecurityError (thus robust web apps should wrap LS access in a try-catch or similar mechanism), and the size of LS is not always equal to 5 MiB (on older Androids it is smaller, for example).

It would be fair to provide a link to MDN: developer.mozilla.org/en-US/docs/W..., which describes LS in greater details.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Session storage would be a better alternative also or no client side storage at all, even better, for legal and security reasons.

Collapse
 
vigyanhoon profile image
Sanjay Pandey

Short and simple, thats how all articles should be. Alas people think more jargons they use, more people see them as geeks.

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

It is a good article, just the subject is a little controversial.

Collapse
 
wendell_adriel profile image
Wendell Adriel

Great article, simple and right to the point.
I had some cases in some projects at my company that I needed to extend how to work with the Local Storage, then I created these two packages here:

github.com/WendellAdriel/time-storage
github.com/WendellAdriel/counted-s...

Depending on which kind of app we're working with, Local Storage can be a good friend!!!

Collapse
 
entioentio profile image
entio

If you just wanna be fine, dandy and secure wherever possible, use this github.com/localForage/localForage

API is pretty similar to localStorage but it uses IndexedDB or WebSQL where possible to allow quick and easy access.

Collapse
 
dago_djanaya profile image
dago

Sara thanks, i really enjoy it your article,n use it before finished it, but i crash with a big wall when i go ahead n try to understand your NoteApp code, im a newbe that happen a lot, kinda like: wtf there is no "package.json" here, how do i install this thing... u know what i mean 😁.

Collapse
 
aibee profile image
Iboro

Lovely piece, need to start using this. Would've liked to see how you implemented your state object though.

Collapse
 
ipurak profile image
Rungrot Suptan

Thanks!! Great article!

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you for reading.

Collapse
 
kyleljohnson profile image
Kyle Johnson

Arguably the most under used thing in web development. Great article!

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you.

Collapse
 
10secondsofcode profile image
Elango Sundar

Detailed explanation about local storage...thanks..keep it up.

Collapse
 
sarah_chima profile image
Sarah Chima

Thanks for reading it.

Collapse
 
efleurine profile image
Emmanuel

Thanks for the details explanation

Collapse
 
sarah_chima profile image
Sarah Chima

I'm glad you like it.

Collapse
 
narthcodes profile image
dumtochukwu

wow i love the article

Collapse
 
jsgoose profile image
Jonathan Sexton

Hi Sarah! I loved your article and would like to include it in my June Newsletter that I send out. I'll put a link to this article and attribute you if you're alright with that?

Collapse
 
sarah_chima profile image
Sarah Chima

Hi Jonathan. Thanks for reading my article. I'm glad you like it. It will be my pleasure for my article to be included in your newsletter.

Collapse
 
jsgoose profile image
Jonathan Sexton

Thank you so very much Sarah! I really appreciate that!

I look forward to your future work!

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Indexedb that is a better alternative.

Collapse
 
iamakomvictory profile image
iamakomvictory

Hi Sarah! I loved your article and would like to make acquaintance to connect on any of your social media may be LinkedIn :)