How to persist state of your React component in local storage

In this part of the React series, you’ll learn how to make use of the web storage to store user/app data so they are still available to use in the render after page refresh or on a subsequent visit.

This no doubt improves the user's experience.

Why do we need this storage?

Sometimes, we interact with a page and pass in data like form inputs; dark mode theme value; todos items etc. As users, you may need the data to be available on page refresh or your next visit.

Here in this section, you’ll learn to do that. To get started, let’s take a look at the Storage API.

A Brief Look at the Web Storage API

Web browsers have a storage unit for every website or application where we can store data. From this storage, we can also retrieve or delete the data. Now, to have access to this storage, the browser provides for us, the Storage API mechanism that allows us to interact with the data. These mechanisms are Local Storage and Session Storage.

The Session storage as the name implies allows us to store data that persists throughout the session. That is, as long as the current browser tab remains active.

On the other hand, the data stored in the Local Storage has no expiration date. The data will not be erased when the browser is closed and it is shared between all windows with the same origin.

Same-origin here implies – same domain (example.com); same protocol (either HTTP or HTTPS) and same port (for instance, port 80 which handles HTTP request exclusively). The URL path can be different.

While the above mechanisms are similar in terms of implementation, our focus is on the local storage. This is because we want our todos data to persist changes across the same origin and not ONLY bound to the current browser tab.

So let’s dive in.

The Local Storage Implementation

If you open the Console of your web browser and type localStorage and then press enter, you’ll immediately have access to the Storage object of the page. In this object, you can access the local storage space.

window.localStorage

// same as this:

localStorage

Note: Since the window object is a global object, we can access its built-in properties without having to type window. Prefix. So both of the above lines are valid.

If you take a careful look at the methods available on the prototype, you’ll see several useful methods. So let’s talk about some of them quickly:

Saving data to local storage

The first method we will look into is the setItem(). We use this method to add an item to the Storage object. This method accepts two arguments – the key name and value.

localStorage.setItem("key", "value")

If the key already exists, then the value gets updated.

Let’s see:

Open the browser console and type the following code:

localStorage.setItem("todos", "data")

Once you press enter, head over to the browser local storage area and see your data.

If you are on Mozilla Firefox: DevTools -> Storage -> Local Storage

Chrome: DevTools -> Application -> Local Storage

It doesn’t get simpler than that.

Note: The storage only accepts strings for both the keys and the values. It converts other data types like the Number and Boolean to string automatically.

Though, most of the time, you’ll be working with a JavaScript object. In this case, we often use JSON to exchange this data type to/from the local storage. You’ll use JSON.stringify() method to convert the JavaScript object to a JSON string.

To retrieve the data and use in your application, you’ll need to re-convert it back to object. You’ll learn how to do that in a moment.

Reading data from local storage

To retrieve or read data from the local storage, you’ll need to invoke the getItem() method and pass along the data key.

So the syntax looks like this:

localStorage.getItem("key")

Now let’s retrieve the data we saved earlier. Remember, we set the data key to todos earlier.

So, go back to the Console and type this code:

localStorage.getItem("todos")

Once you hit the enter button, you should receive your saved data.

Going a step further, let’s apply these methods once again to store and receive JavaScript object.

In the Console, add this code:

const obj = {
  id: 1,
  title: "Setup development environment",
  completed: true,
}

Hit enter and add this line:

localStorage.setItem("myItem", JSON.stringify(obj))

Once you enter the code, the data get stored in the local storage. Please go ahead and take a look.

The area of focus here is the JSON.stringify(obj). This converts the object to JSON string that the storage can handle.

Next, let’s retrieve the data using the getItem() method. In the Console, add this line and hit enter:

localStorage.getItem("myItem")

You’ll receive your data but in the JSON format.

Remember, the storage always returns a string. So we need to make use of the JSON.parse() method to parse the string and returns a JavaScript object.

Your code should now look like this:

JSON.parse(localStorage.getItem("myItem"))

Enter the code in the Console and get a proper JavaScript object.

Good. All of these will come to play when we start storing/retrieving our React todos app data in the local storage.

Removing data from local storage

There are two methods available on the localStorage object that allows us to remove item(s) from the storage. The removeItem() and clear() methods. These methods remove an item and clear the storage respectively.

To remove a stored item from the local storage, you’ll need to invoke the removeItem() method and pass along the item key to remove.

localStorage.removeItem("key")

Let’s apply this method.

If you remove the last stored item (with key myItem) from the local storage, your code should look like this:

localStorage.removeItem("myItem")

To remove all the saved data from local storage, you simply run this code:

localStorage.clear()

Good.

Now you know what the localStorage is and how you can invoke its available methods to manipulate the storage area.

Please note that web storage is not meant to store large amounts of data. There are other options like the IndexedDB that was designed for that. However, using the web storage is sufficient for our use case.

In the next part, you will start learning how we can apply the storage APIs to persist our todos data.

Next part: Getting Started With React Lifecycle Methods

continue