We will discover here how to add values to local storage, how to retrieve them, or delete them.
Table of Contents
Storing Data
To add data to local storage, use the setItem() method of localStorage. The syntax is as follows:
localStorage.setItem(key, value)keyis the key, representing the name associated with the stored value. This is how you will access it later.valueis the value to store, such as a theme or something else. Here, you must provide astring.
For example, for a dark or light theme:
localStorage.setItem('ThemeDark', 'true');
Retrieving Data
To retrieve a stored value, use the getItem() method. The syntax is as follows:
localStorage.getItem(key)With this code, you target a specific key whose value you want to retrieve. The value will be returned as a string. If you want to retrieve a value of another type, like a boolean, in the example, you must use JSON.parse() to convert the string into a boolean.
JSON.parse(localStorage.getItem('ThemeDark'))
Deleting a Key-Value Pair
You can also delete a stored value by using the removeItem() method. It takes the key to delete as a parameter.
localStorage.removeItem(key)In this way, the key and its corresponding value are removed from local storage. Using our example:
localStorage.removeItem('ThemeDark')
Clearing Local Storage
To clear local storage, use the clear() method. It removes all stored key-value pairs.
localStorage.clear()
Retrieving the Key of a Pair
You can use the key() method to find the key of a value at a given index in local storage.
localStorage.key(index)For example, if you want to retrieve the name of the second key:
localStorage.key(1)
Knowing How Many Items are Stored
Finally, you can know the size of local storage using the length() method. This way, you get the number of key-value pairs present in local storage.
localStorage.length()
And the bugs?
You might encounter this error message: ReferenceError: localStorage is not defined. To fix it, simply check if window is defined using a condition.
if (typeof window !== "undefined") {
value = localStorage.getItem(key)
}Additionally, if you want to retrieve a value, I highly recommend using a useEffect to ensure that the method executes at the right time.
Therefore, it's very simple to use local storage with React or Next. You can implement it in a React Context, for example, to set up a theme system, as we do here.
If you want to learn everything about React, take a look at our comprehensive React course.







