Persist Data Client-side with localStorage
Tags: javascript, webdev
Published: 2021-08-09 03:19:47

---
title: Persist Data Client-side with localStorage
published: true
date: 2021-08-06 01:27:05 UTC
tags: javascript,webdev
canonical_url: https://javascript.plainenglish.io/persisting-data-client-side-with-localstorage-f72d96dba7b9?source=rss-530d9586f2f
cover_image: https://cdn-images-1.medium.com/max/2600/0*SGeazie5O9aebep0
---
## What is localStorage?
So what is localStorage you ask? Well, localStorage is simply a Javascript object. But that's not all. It is a part of the Web Storage API which is used by us developers to store data locally on the client side. The localStorage object is one of two that are used to store data on the client (browser).These are the `localStorage` and `sessionStorage` objects. The main difference between these two types of storage objects is that localStorage is used for storing data while the browser is open but also when it's not, meaning data is persisted after the browser is closed. With sessionStorage, the storage for your data is only available while the browser is still open.

So why use localStorage or sessionStorage?

Before HTML5 came along only cookies were used to store data. Cookies are sent on every request to the server, they offer less storage space (about 4kb) and less security than localStorage and sessionStorage. With localStorage, there is up to 5MB of space and no expiration date for storing data.

## When to use localStorage
Whenever you want your client-side data to persist so it doesn't disappear on page reload like with sessions then localStorage can be a great option. For example, if you're building a chrome extension you might want your extension to be able to store data and have it be available across page refreshing.

## How to use localStorage
To use localStorage we must first access it through the global `window` object. When we invoke localStorage from the `window` object what we get is an instance of the `Storage` object which allows us to set, get, and remove data items for both session and local storage types.
```
> window.localStorage
► Storage {length: 0}
```
For simplicity, we'll just use a variable to reference our `window.localStorage` here.
```
const myLocalStorage = window.localStorage
```
To start using our localStorage let's quickly go over the five different methods available for it.

* `setItem()` Sets a key/value pair to be stored as strings for localStorage
* `getItem()` Gets a data item from localStorage by referencing the key
* `removeItem()` Removes specific data items from localStorage by key
* `clear()` Clears localStorage completely
* `key()` Accepts an index number to grab the name of a key in localStorage

Let's see some of these methods in action using `myLocalStorage`.
```
// set up localStorage key and value
myLocalStorage.setItem("Name", "Tim Berners-Lee");

// retrieve the Name value
myLocalStorage.getItem("Name"); // Tim Berners-Lee

// access the Name key
myLocalStorage.key(0) // Name
```
Now our localStorage appears as the following:
```
► Storage {Name: "Tim Berners-Lee", length: 1}
```
Then, if we want to remove data from localStorage we can use the `removeItem()` method to remove a specific data item or `clear()` which will completely empty out the storage. In this case, both will do the same as we only have one key/value pair to remove.
```
myLocalStorage.removeItem("Name")
// Or
myLocalStorage.clear()
```
This will delete our key/value pair from myLocalStorage :
```
► Storage {length: 0}
```
What if we wanted to store other data types in `myLocalStorage` instead of just hard coding strings as the value? This is where `JSON.stringify()` and `JSON.parse()` come in. Let's store our data item from before as an object with another property added, then convert the object to a JSON string and pass it to `setItem()`:
```
const inventorOfTheWeb = {
    name: "Tim Berners-Lee",
    organization: "W3C"
}
localStorage.setItem("person", JSON.stringify(inventorOfTheWeb))
```
Now our storage will look like the following:
```
► Storage {person: 
"{'name':'Tim Berners-Lee','organization':'W3C'}", length: 1}
```
And if we need to retrieve our `person` from storage, we can just parse it using `JSON.parse()` to construct it back into an object:
```
let storedPerson = JSON.parse(localStorage.getItem("person"))
```
## Conclusion
In this article, we went over the basics of storing data on the web with localStorage. We also briefly mentioned the other ways of data storage with sessionStorage and cookies. Each of these has its own use case so it will depend on your specific situation in choosing which to implement for your application. If you need to store data client-side without an expiration date and with a larger storage capacity then localStorage may be the way to go!