Store it, locally

Mary Kang
The Startup
Published in
3 min readMay 7, 2020

--

I recently learned about a neat little tool called localStorage, so I figured I would do a little reading on it to gain a clearer understanding, and then try to put that understanding into my own words.

But first, let’s backtrack a bit. So… not in my own words, but according to MDN web docs:

When writing code for the Web, there are a large number of Web APIs available. The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.

Brief Overview of Web Storage

There are two different mechanisms for Web Storage — sessionStorage and localStorage.

First, let’s take a look at what they both offer:

Photo by Zachary Keimig on Unsplash

Storage: ability to set, retrieve, and remove data locally in the browser; data stored is specific to the protocol of the page

Window: an extension of the Windowwith the new storage property, and a Window.onstorageevent handler that fires when the storage area changes

StorageEvent: astorageevent fires when the storage area changes (for example, a new item is set to storage).

Strings: only supports key/value strings; other datatypes are automatically converted

Size: most modern browsers allow 2 megabytes of data at minimum

Now, let’s understand the differences:

sessionStorage: data persists until the browser window is closed

localStorage: data persists until it is manually cleared, even after browser window is closed + data is shared between all tabs and windows with the same origin

Web Storage Methods

  • setItem (key, value)- store the key and value pair
  • getItem (key)- retrieve the stored value by the key
  • removeItem(key)- remove the key/value pair by key
  • clear()- remove all stored data
  • key(index)- retrieve the key on a given position
  • length- returns the number of stored items

Examples

Check if localStorage is supported in the browser and if anything is currently stored:

Add data tolocalStorage:

Get data fromlocalStorage:

Update data inlocalStorage:

Delete data inlocalStorage:

Clear all data inlocalStorage:

Adding JSON objects tolocalStorage:

Since localStorageonly supportsstrings, we use JSON.stringify()to convert our object to a string

However, getting this item again would result in:

"{"toppings":"Pineapple and Ham","scandalous":"very"}"

Get JSON objects fromlocalStorage:

We use JSON.parse() to convert the contents back into our datatype.

Use Cases

Web storage is commonly used for saving data such as user preferences, remembering items saved in a shopping cart, and keeping track of that a user is logged in.

Although cookies can be used for similar types of storage, they have significantly lower storage limits, and send data to the server with every HTTP request.

Check out the MDN docs here for further information to help you decide which Web Storage mechanism might be best for your application.

--

--