LocalStorage in React

Topics Covered

Overview

Local storage is a web storage object for storing data locally on the user's computer. This means the data is stored in the user session and, unlike cookies, does not expire. You can access storage objects using the localStorage() API.

All kinds of data can be stored in storage objects. This is a built-in hook, so you don't need to import anything. The best and most common practice is to store data first in the state and then in storage objects.

Introduction

Local Storage is a web storage object for storing data locally on the user's computer. This means that saved data is saved between browser sessions and saved data never expires.

Local Storage is one of the easiest ways to store data on the client side. The best thing about local storage is that your data won't be removed from your browser unless you clear your browser's cache.

Syntax

Getting Started

  • Initial localStorage project setup

If you want to follow the example used in this article, set up a simple React project using create-react-app by running the following command in your computer's terminal:

After completing the folder setup, start your project by running the command:

  • Creating a React form component

After the project is set up and cleaned up, we can create a form component to work with. First, create a components folder inside the src folder and add a form component to it.

Form.js

Explanation

It is a simple Form component that has two input fields. One is for writing the text and the second one is a checkbox for toggling Remember me and a button is for submitting the form after running the code you saw something like this.

Form Component

The code required to handle the state of the form components is also comprehensive.

Form.js

Explanation

The code snippet above:

I use React's useState hook here. And the initial useState value is an empty string. After that, we provide a value for the input field. And after that, we add onChange for set and update the value again and again when the button is pressed.

Input data is not retained at this time. The input data is deleted when the page is refreshed. Persist input data so it is available after each page refresh and on subsequent page visits.

How to Implement LocalStorage in React

LocalStorage has five methods:

  • setItem(): This method is used to add a key and value to localStorage.
  • getItem(): This method is used to get an item from localStorage using its key.
  • removeItem(): This technique is used to remove an item from localStorage based on its key.
  • clear(): This technique is used to clear all instances of localStorage.
  • key(): Specify a number to help get the localStorage key.

How to Use the setItem() Method

You can use setItem() to set items in localStorage that persist across page reloads.

A small use case for this is when data is added to localStorage when a button is clicked.

Objects, strings, and even arrays can be set to localStorage.

To find out where the localStorage element is:

  • Right-click and click Inspect.
  • When you navigate to the application, you'll see an item in the name of the website you're currently viewing.

How to Use the getItem() Method

After setting the data, you can access it using localStorage.getItem("data").

Now you can get the element as a string using JSON.stringify() or from a string as an object using JSON.parse().

You can then use this data to map to your frontend or any other logic you want.

How to Use the removeItem() Method

You can remove localStorage items using localStorage.removeItem('data').

The use case is similar to setItem(). If you want to delete the item, click the button to complete this function.

How to Use the clear() Method

This function allows you to remove all elements at once.

Problems Accessing LocalStorage for an SSR Application

Local storage is a built-in property of the browser window's object. For connecting the means prefixing each window with dot notation, like this:

But looking at the code, I see that I ignored the widget when accessing local storage. But the code runs fine. This is because widgets are global objects and adding to memory properties is optional.

However, this is not the case for frameworks such as Next.js and Remix.js that run code on the server side. Widgets are not server-side available, so using memory properties such as local memory will throw a window undefined error.

For fixing the undefined error, you have to check in the current environment that the window object is defined before executing the code. After that only you can run the code in environments.

To do this, go back to your useLocalStorage.js file and update the getStorageData function as follows:

Explanation

The code above wraps the logic inside the getStorageData function with an if statement. This statement checks if the widget is defined in the current environment.

Fuel Your Full-Stack Passion! Our Full Stack Web Development Course Blends JavaScript Brilliance with Back-End Craftsmanship. Ready to Dive In? Enroll Now!

Conclusion

  • Using localStorage in React is very easy. Easily find the best time to save and restore your data. This is different for each component.
  • You learned how to store data using localStorage and retrieve it using React hooks.
  • We've seen how to use localStorage to store form and state data in your Reactjs application.
  • For front-end developers, localStorage is a lifesaver. Because backends and database concepts like node.js and MongoDB don't require the use of routes (like GET or POST) in static apps.
  • Data in localStorage persists between browser sessions. This means that even if you close and open your browser, this data will persist.
  • localStorage is a web storage object that allows javaScript websites and apps to store key-value pairs in the web browser without expiration.