Using Local Storage for a Persisting State
Learn how to use the Local Storage API to store data inside the user's browser.
We'll cover the following
Before we begin, let’s look at what the Local Storage API is. The Local Storage API allows us to save and read data to a user’s browser. This data is kept so we can retrieve it even after the user closes their browser. There is no expiration date on the data, and it is stored locally on the user’s machine.
We should make it clear that local storage should not be confused with session storage, which is an API similar to local storage. A difference is that for session storage, the data is clear after the user leaves the page; however, with local storage, the data is persisted.
Why use local storage?
Using local storage for any application (not just with Svelte) is a great and easy way to store information in the browser for internally used applications. The application we'll build is a fully client-side application, meaning there will be no server required for us to use the application. All data will be stored on the client.
This also has cost benefits because there is no need to rent additional servers or databases. It has speed benefits as well since we're not reliant on network requests. The biggest advantage is that if we have the application files locally on our device, we can also use them in an offline environment.
On the other hand, there are pros and cons for every approach. The biggest downside would be that since the data is stored in our local machine, we won't be able to access the data on other devices unless we export it and reimport it elsewhere. We'll look into how to do this in future lessons.
Get hands-on with 1400+ tech skills courses.