localStorage is a great, powerful tool for persisting information between sessions. To disambiguate that sentence, sessionStorage lasts for as long as the browser tab is open--this includes page refreshes and restores. However, localStorage persists data even when the browser or tab is closed then reopened. It essentially acts as a mini database on the client.
Although, we shouldn’t solely construct our websites around localStorage because not all browsers or tabs have localStorage or sessionStorage enabled. For example, in a browser’s private browsing mode, localStorage may be turned off--hence the key word “private”. Or, a user may intentionally disable it on the browser globally. As such, our code would throw errors and render our website useless. You should always handle these errors, but again, we may want to stray away from relying on localStorage in order for our websites to function.
For example, I built a website for a small business that solely relies on localStorage. It is an expense and budgeting web app.
Anyone who uses the website with localStorage disabled would not be able to effectively use the website. However, knowing that this web app was only for a single business and not for the masses, I moved forward with using localStorage, notifying the customer that localStorage needs to be enabled in order to use the website.
Anyway, accessing the Web Storage API is easy as using a few methods. These methods are used to store key/value pairs. For example, the setItem() method is used to store a new key/value pair:
Additionally, if the key already exists, the setItem() method updates the key with the new value that’s passed in. Just remember to JSON.stringify() any object that you pass into localStorage.
When you want to retrieve a value previously set in localStorage, use the getItem() method.
If the item doesn’t exist, null will be returned. Otherwise, it will return the value associated with that key. Again, just remember to JSON.parse() any object that you previously stringified with JSON.stringify() and set using localStorage.setItem().
To remove any one key/value pair, we can use the removeItem() method. Just pass in a key. And finally, if you want to remove everything stored in localStorage, use the clear() method.
For more information regarding the Web Storage API, and detecting if localStorage is enabled on the client, visit MDN.