Introduction
In today’s web applications, providing a seamless experience across sessions is crucial for keeping users engaged. Imagine filling out a form, navigating away, and returning to find all your progress saved—this is the magic of state persistence! One popular and simple way to achieve this is through the localStorage Web API.
In this blog, we’ll walk you through how to save and restore the React state using local storage in a React TypeScript Application. We’ll cover practical examples, explore when this approach is most useful, and compare it to other storage options like session storage and cookies.
Prerequisites
- Node.js and npm
- React
- Typescript
- JSON.parse() and JSON.stringify()
What is the LocalStorage?
Local storage is a web storage that allows users to store data as key-value pairs and retrieve the data in the browser. It’s a simple, synchronous API where the data is stored as strings and remains available even after the browser is closed, making it ideal for persisting data across sessions.
Common Use Cases
Here are some scenarios where persisting state using local storage is beneficial:
- Theme Persistence : Retain user preferences like light/dark themes across sessions.
- Shopping Cart Data : Store items added to a cart so users can return later and see their selections.
- Form Data : Persist on partially completed forms so users can complete them later without losing progress.
- Authentication Tokens : Store JWT tokens or session information.
Key features
- Persistent Data : Data stored in localStorage remains even after the browser is closed and re-opened. It only gets deleted if the user explicitly clears the storage or your code removes it.
- Storage Limit : Each domain has approximately 5MB of storage available. This limit varies slightly across browsers but is usually sufficient for most use cases.
- Stores Only Strings : localStorage can only store string data. If you need to store objects or arrays, you have to convert them to strings using JSON.stringify() and parse them back with JSON.parse() when retrieving them.
- Synchronous API : Interacting with localStorage is synchronous, meaning it can block the main thread. For small operations, this is usually not noticeable, but for large datasets or frequent reads/writes, this can impact performance.
Methods
- setItem() : This method allows the user to store the data as key-value pairs in local storage. It takes two parameters key and value.
Syntax : localStorage.setItem(key,value)
- getItem() : This method allows the user to retrieve the data using the key from local storage. It accepts only one parameter, the key, and returns the value as a string.
Syntax : localStorage.getItem(key)
- removeItem() : This method allows the user to Remove specific data using its key from localStorage. When you pass a key name to the removeItem() method, it deletes the item associated with that key from localStorage. If there’s no item with that key, this method will do nothing.
Syntax : localStorage.removeItem(key)
- clear() : This method allows the user to Remove all stored data from the localStorage.
Syntax : localStorage.clear()
- key() : This method is used for the key at a specific index.
Syntax : localStorage.key(index)
- length() : This method Gives a number of items stored in the localStorage.
Syntax : localStorage.length()
Comparison with Other Storage Types
Features | Local Storage | Session Storage | Cookies |
Persistent | Persistent across browser sessions | Available only during the session | Can be persistent if expiration is set |
Storage Limit | ~5MB | ~5MB | ~4kb |
Data Type | String only | String only | Can store any data type |
Expires | Never (unless manually deleted) | When the session ends | Can set expiration time |
Accessed by Server | No | No | Yes |
Frontend Setup in React
We’ll create a user form in React that allows users to enter their name and email. The form data will be saved to localStorage to ensure the information persists even after a page refresh or browser restart.
Step-by-step Implementation
- Create a React App
Let’s create a React app using the following command:
//Create a react app using the following command
npx create-react-app local-storage-app --template typescript
After the setup is complete, navigate to your project folder:
// Navigate to project folder
cd local-storage-app
npm start
This will launch the development server, and you’ll be able to view the app at http://localhost:3000.
- Project Structure
Make sure your project has the following folder structure:
- Create the UserForm Component
We’ll create a separate UserForm component inside the components folder to handle user data entry and manage state for name and email. The component will store the data in localStorage so that it persists even after a page refresh or browser restart.
//UserForm.tsx
import React, { useEffect, useState } from "react";
interface UserData {
name: string;
email: string;
}
function UserForm() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [userData, setUserData] = useState(null);
const addUserData = (e: React.FormEvent) => {
e.preventDefault(); // Prevent the default form submission behavior
localStorage.clear(); // Clears all the data
const userData = {
name,
email,
};
localStorage.setItem("userInfo", JSON.stringify(userData));
setName("");
setEmail("");
};
const removeUserData = () => {
localStorage.removeItem("userInfo");
setUserData(null);
};
const getUserData = () => {
const storedUserInfo = localStorage.getItem("userInfo");
if (storedUserInfo) {
const userInfo = JSON.parse(storedUserInfo);
setUserData(userInfo);
}
};
useEffect(() => {
getUserData();
}, []);
return (
);
}
export default UserForm;
- Integrating the Form into the App
Now, we’ll import the UserForm component into the main App.tsx file. This component will render the form UI and persist the user data.
//App.tsx
import React from "react";
import UserForm from "./components/UserForm";
function App() {
return (
Persisting React state in Localstorage
);
}
export default App;
Here’s a detailed breakdown of the above code and how localStorage handled the data in a react.
Storing data in the LocalStorage
When the user submits the form, the addUserData function is called. This function stores the name and email in the browser’s localStorage under the key “userInfo“.
//Store data in the LocalStorage
const addUserData = (e: React.FormEvent) => {
e.preventDefault(); // Prevent the default form submission behavior
localStorage.clear(); // Clears all the data
const userData = {
name,
email,
};
LocalStorage.setItem("userInfo", JSON.stringify(userData));
setName("");
setEmail("");
};
- The function starts by clearing all data from localStorage using localStorage.clear(). While this ensures we are working with a clean slate, it’s important to note that it wipes out all saved data in localStorage, not just the user-related data.
- Next, a user data object is created, which holds the values of the name and email properties. These values are typically obtained from the form fields or state variables in React.
- The userData object is then stored in localStorage using the localStorage.setItem() method. Since localStorage can only store strings, we use JSON.stringify() to convert the userData object into a JSON string.
- Now, the user’s information is safely stored in localStorage under the key “userInfo”. This means you can access it later, even if the user refreshes or closes the page.
- After saving the data to localStorage, the function calls setName(“”) and setEmail(“”) to clear the input fields, which resets the name and email state variables back to empty strings. This ensures the form fields are empty after submission.
Retrieve the data from the LocalStorage
We retrieve the stored user data using the getUserData function, which runs on component mount thanks to useEffect(). If the data exists, it is displayed in the UI.
//Retrieve data in the LocalStorage
const getUserData = () => {
const storedUserInfo = localStorage.getItem("userInfo");
if (storedUserInfo) {
const userInfo = JSON.parse(storedUserInfo);
setUserData(userInfo);
}
};
- To retrieve the stored user information from the localStorage using localStorage.getItem(“userInfo”), which fetches the data saved under the key “userInfo”.
- If no data is found under the “userInfo” key, stored UserInfo will be null. That’s why we need to handle this case next.
- If storedUserInfo is not null, it means that there is saved user information available. Since data in localStorage is stored as a string, we need to convert it back into an object. This is done using JSON.parse() method.
- Once the userInfo object is available, we update the userData by calling setUserData() with the retrieved values.
Remove the data from the LocalStorage
Once user data is stored in localStorage, there might be situations where you want to delete it, for example, when a user logs out or resets the form. The removeUserData function demonstrates how to remove specific data from localStorage by targeting a particular key. Let’s break it down:
//Remove data in the LocalStorage
const removeUserData = () => {
const storedUserInfo = localStorage.removeItem("userInfo");
setUserData(null);
};
The function calls localStorage.removeItem(“userInfo”) which removes the item stored under the key “userInfo” from localStorage.
The localStorage.removeItem(“userInfo”) function is used to remove the item associated with the key “userInfo” from the browser’s local storage. This targeted approach is preferable to localStorage.clear(), which deletes all items from local storage. By specifically removing only the user data linked to the “userInfo” key, we enhance security and maintain the integrity of other stored data.
Use Cases for Removing Data from LocalStorage
- Logging Out : When a user logs out of the application, you may want to clear their data from local storage for security reasons.
- Resetting Form : If the user resets a form or decides to start over, you can remove their previously entered data from localStorage.
Conclusion
LocalStorage is a powerful feature in React that allows developers to efficiently store and retrieve data in a user’s web browser. By leveraging localStorage, applications can persist user information and session data even after a page refresh or when the browser is closed, ensuring a seamless and personalized user experience. This capability enhances application functionality and contributes to a more user-friendly interface, enabling the creation of responsive and dynamic web applications. Ultimately, effective use of localStorage can significantly boost user satisfaction and engagement.