How to Use localStorage to Persist the State in React
-
What Is
localStorage
in React -
Using
localStorage
Methods in React -
a Practical Example of
localStorage
in React
Single Page Applications are very popular today, mainly due to their speed and superior user experience. Many libraries and frameworks exist for building SPAs, but React is the most popular; it utilizes Virtual DOM
to update the screen with the page’s most recent and up-to-date version.
In React, the state
is an important concept because the changes in the state
or props
trigger the re-render of specific components. There are many ways to maintain the state and update its values.
One way is to have a simple state
object to maintain the values. A more advanced option is to persist the state to localStorage
.
React developers use libraries like redux
for state management for complex projects. In this article, we want to explore the localStorage
approach.
What Is localStorage
in React
In simple words, localStorage
is a feature of the browsers to store or persist the data for later use. For instance, if you maintain a regular state
object in your React application, it’s impossible to maintain the state
values after closing the tab or entire browser.
The localStorage
persists the data even if you close the browser, making it ideal for persisting the data when you’re building your application or want to build a local JavaScript application in React. For instance, if you have a to-do application, you don’t want to lose all the data about your to-dos when you close the application.
You can use localStorage
to ensure that the data won’t be lost even if you close the browser.
You can use localStorage
with class components and functional components. The main method for updating the state for class components is the setState()
method.
We have the useState()
hook in functional components, creating a state variable and an updater function.
Using localStorage
Methods in React
Typically React developers use localStorage
to store the key-value data they want to persist in their application. There’s a certain API for maintaining the values in localStorage
.
One of the most common operations with localStorage
is to create the records with key-value pairs using the localStorage.setItem()
method. It accepts two strings as arguments: representing key
value and one representing the value
itself.
For instance, localStorage.setItem('Name', 'George')
will create a data record with a key-value pair of Name: George
. The localStorage.getItem()
method accepts one string argument to represent the key, and it allows us to read the value of that key.
For example, we could read the value of the Name
key like this: localStorage.getItem('Name')
.
You can also remove a specific key-value pair using the localStorage.removeItem()
method. It accepts one argument, the string value, to denote the key
value that must be removed.
For instance, localStorage.removeItem('Name')
will remove the key-value pair we recently added. Finally, the localStorage.clear()
method doesn’t need any arguments and will automatically wipe out every key-value pair in the localStorage
.
a Practical Example of localStorage
in React
Let’s explore the practical benefits of localStorage
in React and build a simple application that responds to users’ actions and changes the element’s style accordingly.
However, you must consider that localStorage
is not a built-in feature of React. If you update the regular state values in React, the component will automatically re-render.
However, changing the value of the localStorage
object keys does not automatically update the component. Instead, we can read the value from localStorage
using the getItem()
method on the API.
If you check the live demo on CodeSandbox, you’ll see that the changes aren’t immediately visible after making changes to localStorage
. To make sure your app responds to users’ input immediately, you need to update the local state values.
In this case, we have a functional component, so we use the useState
hook to create the state variable and the function for updating it. Then we define an event handler that updates the value in the localStorage
and the local state variable all at once.
import { useState } from "react";
export default function App() {
const [bgColor, setBgColor] = useState("");
const handleClick = (color) => {
localStorage.setItem("color", color);
setBgColor(color);
};
return (
<div
style={{ backgroundColor: localStorage.getItem("color"), height: 500 }}
>
<button onClick={() => handleClick("pink")}>Pink</button>
<button onClick={() => handleClick("blue")}>Blue</button>
<button onClick={() => handleClick("purple")}>Purple</button>
</div>
);
}
Even though we never directly read the state value, we still need to update it to ensure that the component is re-rendered with the most recent value from the localStorage
.
Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.
LinkedIn