• Articles
  • Tutorials
  • Interview Questions

LocalStorage in ReactJS

LocalStorage in ReactJS

In this blog, we will delve into the intricacies of localStorage in ReactJS, unearthing its potential and exploring how it may improve the functionality and user experience of applications. 

Watch the video below to learn React JS from scratch:

What is LocalStorage in ReactJS?

Within JavaScript, localStorage serves as a web browser feature that empowers web applications to securely store data on a user’s computer. It provides a simple key-value storage mechanism that can be accessed and modified by JavaScript code running in the browser.

LocalStorage is like a small storage container that belongs to a specific website or web application. It is similar to cookies but with a few important differences. Cookies are primarily used for storing small amounts of data sent back and forth between the web server and the browser with each request. However, localStorage is designed for larger amounts of data that need to be stored on the user’s computer for a longer period of time.

You can use the localStorage object, which is integrated into current web browsers, to leverage localStorage in JavaScript. This object contains methods for storing, retrieving, and removing data from localStorage. It is exemplified in detail below:

  • To save a value in localStorage, you can utilize the setItem() method, which allows you to specify a key-value pair. For instance, if you intend to store a user’s name, you can achieve this by following the code snippet below:
localStorage.setItem('name', 'ABC');

For instance, this can store a value “John” with the key “name” in the localStorage.

  • In order to obtain a value from localStorage, the method employed is getItem(), where the respective key is supplied as an argument. To illustrate, if one intends to retrieve the user’s name, this can be achieved by invoking the getItem() method with the appropriate key.
var name = localStorage.getItem('name');

The variable name will now contain the value “John” if it was previously stored in localStorage.

  • If the intention is to eliminate a value from localStorage, the recommended approach involves utilizing the removeItem() method and providing the corresponding key. As an illustrative instance, consider the scenario where the removal of a specific value is desired: one can achieve this by invoking the removeItem() method and specifying the appropriate key.
localStorage.removeItem('name');

This will erase the value associated with the key “name” from localStorage.

Localstorage is limited by the amount of space available on the user’s computer. Each website or web application has its distinct localStorage. As a result, data kept by one website cannot be viewed or updated by another.

Learn React JS by enrolling in our React JS Training Course today!

How to Get Data from LocalStorage in ReactJS

To save and retrieve data from ‘localstorage’, you may utilize the localStorage object in ReactJS, which is integrated into current web browsers. Follow these steps to obtain data from localStorage in a React component:

Step 1: Using React to Access localStorage

To utilize the ‘localStorage’ feature within a React component, it is necessary to import the ‘localStorage’ object from the ‘window’ object. To achieve this, include the following import statement at the beginning of your React component file:

import React from 'react';

Step 2: Retrieving Data from localStorage

To obtain data from localStorage, utilize the getItem() function given by the localStorage object. This is usually done within a lifecycle function or an event handler in your React component. For example, if you wish to access a user’s name from localStorage, you may use the following code:

import React, { useEffect, useState } from 'react';
function MyComponent() {
  const [name, setName] = useState('');
  useEffect(() => {
    const storedName = localStorage.getItem('name');
    if (storedName) {
      setName(storedName);
    }
  }, []);
  return (
    <div>
      <h1>Hello, {name}!</h1>
    </div>
  );
}
export default MyComponent;

In the provided example, the useEffect hook is employed to fetch the stored name from localStorage upon the component’s mounting. By utilizing an empty dependency array ([]), the effect is executed solely during the initial rendering of the component. Within the effect, the stored name is retrieved via the ‘localStorage.getItem(‘name’)’ method and subsequently assigned to the component’s state using ‘setName(storedName)’. If the name is indeed present in localStorage, it will be displayed within the rendered JSX.

Get 100% Hike!

Master Most in Demand Skills Now!

Step 3: Handling Data Not Found in localStorage

It’s possible that the desired data may not exist in localStorage when you try to retrieve it. In such cases, the getItem() method will return null. To handle this scenario, you can add a conditional check to set a default value or handle the absence of data in a way that suits your application’s logic.

useEffect(() => {
  const storedName = localStorage.getItem('name');
  if (storedName) {
    setName(storedName);
  } else {
    setName('Guest'); // Setting a default value if 'name' is not found in local storage
  }
}, []);

By setting a default value like ‘Guest’ in the above example, you ensure that your component displays a fallback value when the desired data is not found in localStorage.

Now you know how to retrieve data from localStorage in ReactJS. Remember to use the localStorage object’s getItem() method and handle scenarios where the data may not exist in localStorage.

Check out our blog on React Interview Questions if you are preparing for a job interview. 

Major Differences Between LocalStorage and SessionStorage in ReactJS

Local Storage and Session Storage are web browser features that allow web applications to store data locally on a user’s computer. However, they have some important differences in terms of data persistence and scope.

Data Persistence:

  • LocalStorage: Data stored in localStorage persists even when the user closes the browser or restarts their computer. It remains available until explicitly removed by the web application or cleared by the user.
  • SessionStorage: Data stored in sessionStorage is available only for the duration of the user’s browsing session. It is cleared when the user closes the browser or navigates away from the website.

Scope:

  • LocalStorage: Data stored in localStorage is accessible across different browser tabs or windows of the same origin (i.e., the same website or web application). This allows data to be shared and accessed by different components or pages within the same website.
  • SessionStorage: Data stored in sessionStorage is specific to a single browser tab or window. It is not accessible by other tabs or windows of the same origin.

Data Sharing:

  • LocalStorage: LocalStorage data is shared by all instances of a web browser for a single website or web application. This implies that the user may access and edit the same data stored in localStorage if they open numerous tabs or windows on the same website.
  • SessionStorage: Each tab or window in a browser has its own segregated sessionStorage. Data in sessionStorage is not shared between tabs or windows of the same website.

Crack your next job interview with ease. Find the most commonly asked Javascript Interview Questions and Answers for 2024 here!

Differences in a Glimpse

LocalStorage Vs. SessionStorage
BasisLocalStorageSessionStorage
Persistence of DataData is retained even if the browser is closed or the machine is restarted.When the browser is closed or the user navigates away from the website, data is wiped.
ScopeData can be accessed from several browser tabs/windows of the same origin.The data is unique to a particular browser tab/window.
Data ExchangeAll instances of the web browser for the same origin share data.Each browser tab/window has its own separate storage space.
UsageSuitable for long-term data storage, user preferences, caching, and other applicationsSuitable for storing temporary data throughout a browser session
AccessibilityIt is accessible through many components or pages on the same website.Others cannot access the current browser tab/window since it is isolated.

Check out our ReactJS Tutorial to ace the domain of Frontend Web development. 

Conclusion

Finally, localStorage is a useful ReactJS feature that allows developers to store and retrieve data locally within a user’s web browser. It allows you to preserve user preferences, session information, or any other data that has to be saved between page refreshes or even browser sessions. Developers may build seamless and personalized user experiences in ReactJS by utilizing the localStorage API, boosting the overall usability and functionality of their apps. 

However, because sensitive information kept locally might be subject to malicious attacks, it is critical to utilize localStorage with caution and consider any security and privacy concerns. Overall, ReactJS localStorage is a strong technology that allows developers to construct dynamic and responsive online apps with increased user interactions.

In case of any doubts, drop your queries on our !

Course Schedule

Name Date Details
Web Development Courses 09 Nov 2024(Sat-Sun) Weekend Batch View Details
16 Nov 2024(Sat-Sun) Weekend Batch
23 Nov 2024(Sat-Sun) Weekend Batch

About the Author

Techical Research Analyst - Front End Development

As a Technical Research Analyst, Kislaya specializes in Front End Development. He is a Full Stack Developer, known for crafting scalable architectures and user-centric interfaces. He has a massive international client base and is an expert in cloud computing, Linux, and Java Script, personifying a commitment to quality and information sharing.