Using LocalStorage for Quick Persistent State


TAGS: javascript

LocalStorage is handy in a pinch when you don't have any better solution for saving some form of state between sessions.

In my arcade game Dogger I save the scores to Local Storage so the user can compete against their personal best. LocalStorage is also handy for persisting a user's preference for Dark Mode, if your site offers it.

LocalStorage Methods

LocalStorage comes with a few methods to help us out.

Set Item

localStorage.setItem('highScore', '1500');

Get Item

To retrieve the data from localStorage:

const highScore = localStorage.getItem('highScore');

Remove Item


Clear Everything

This removes everything from localStorage on this current website. This won't affect the localStorage from other sites.


Using with LocalHost

You'll run into an issue when developing locally, as localStorage is all domain based. It helps if you make your key specific to the account or project you're on.

So instead of just doing:

localStorage.setItem('highScore', '1500');

You'd do something like this:

localStorage[account.id] = JSON.stringify({ highScore : 1500 });