Tip 46: Maintain State Over Time with LocalStorage
In this tip, you’ll learn how to save user data with localStorage.
We'll cover the following
Preserving user data
Users love to personalize applications. Conversely, they hate entering the same data every time they visit an app or a page. When you’re working with front-end JavaScript, you’re in a bit of a bind. How do you preserve user data with minimal interference?
An obvious solution is to create a login. The problem is that many users will abandon a site if they’re forced to log in. A better, albeit imperfect, solution is to store data locally. When you save data locally, you can preserve information on a particular browser on a particular device.
Of course, everyone uses multiple devices. So saving data to a browser won’t help a user who works across multiple devices. Still, it’s far less intrusive than demanding a user make yet another account.
Using localStorge
to store user data
You can easily save user information with localStorage
. localStorage
is like a tiny database that exists only in your browser. You can add and retrieve information from it, but it isn’t accessible by JavaScript in the browser.
Think back to your pet adoption site from Tip 13, Update Key-Value Data Clearly with Maps. You set up a series of filters to show only relevant pets. Because pet owners tend to prefer certain types of animals—lovers of labradors probably won’t look for tiny dogs—you could do them a favor if you save their searches between sessions.
Start by saving a breed
preference. To save a breed
, you just need to set the
value on the localStorage
object using the setItem()
method. You pass the key
as the first argument and the value as the second. The syntax should look
familiar. It’s nearly identical to the method for setting data on a map
.
Get hands-on with 1400+ tech skills courses.