Tell us about your project

storage image

With Javascript playing such a huge part in today's front-end development, it comes as no surprise that React, one of JS’ most popular frontend frameworks, is seeing a constant influx of new users.

Being a frontend-exclusive framework React offers a very gentle learning curve on one hand, but has some notable downsides when it comes to developing a more complexly demanding Application. One of the most notable fallacies of a purely React-developed Application is data persistence. What this means is that saving data that should last longer than, let’s say next page refresh, is not as simple as saving it to the database, since there is no database in a React-only App, to begin with.

No need to worry though, there are several mechanisms and services that come into play to help with the problem of data persistence without the necessity of setting up a cumbersome MySQL database. As a matter of fact, setting up a database for the task of keeping a few variables persistent is a huge overkill and should generally be avoided.

Two of the main mechanisms in front-end development when it comes to data persistence are localStorage and sessionStorage.

These do almost the same thing, even use the same API, with the main difference being when the storage itself is cleared. Session storage holds data until the current user session is active. In most cases, this would mean that the data will be lost when the browser or tab is closed. On the other hand, data stored in localStorage will persist even through that and will only be cleared when the browser cache is deleted or the data is problematically cleared.

As far as the syntax goes, both mechanisms use mostly the same syntax:

 

Setting data for a specific key:

localStorage.setItem('storageKey')

sessionStorage.setItem('storageKey')

 

Getting data from storage saved under a specific key:

localStorage.getItem('storageKey')

sessionStorage.getItem('storageKey')

 

Removing a key-value pair from storage:

localStorage.removeItem('storageKey')

sessionStorage.removeItem('storageKey')

 

Clearing entire storage:

localStorage.clear()

sessionStorage.clear()

 

One important thing to note in both cases is that only string values can be saved in the storage. This means that if one would want to save, for example, an object, they would have to run it through a JSON.stringify() method before saving it and then JSON.parse() when reading it.