Blog Blog Posts Business Management Process Analysis

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. 

Table of Contents

Watch the video below to learn React JS from scratch:

{
“@context”: “https://schema.org”,
“@type”: “VideoObject”,
“name”: “React JS Full Course | Learn React | Intellipaat”,
“description”: “LocalStorage in ReactJS”,
“thumbnailUrl”: “https://img.youtube.com/vi/LM1QcJyyagU/hqdefault.jpg”,
“uploadDate”: “2023-08-07T08:00:00+08:00”,
“publisher”: {
“@type”: “Organization”,
“name”: “Intellipaat Software Solutions Pvt Ltd”,
“logo”: {
“@type”: “ImageObject”,
“url”: “https://intellipaat.com/blog/wp-content/themes/intellipaat-blog-new/images/logo.png”,
“width”: 124,
“height”: 43
}
},
“embedUrl”: “https://www.youtube.com/embed/LM1QcJyyagU”
}

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:

localStorage.setItem('name', 'ABC');

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

var name = localStorage.getItem('name');

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

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 (
    

      

Hello, {name}!


    

  );
}
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.

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:

Scope:

Data Sharing:

Differences in a Glimpse

LocalStorage Vs. SessionStorage
Basis LocalStorage SessionStorage
Persistence of Data Data 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.
Scope Data can be accessed from several browser tabs/windows of the same origin. The data is unique to a particular browser tab/window.
Data Exchange All instances of the web browser for the same origin share data. Each browser tab/window has its own separate storage space.
Usage Suitable for long-term data storage, user preferences, caching, and other applications Suitable for storing temporary data throughout a browser session
Accessibility It 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 community page!

The post LocalStorage in ReactJS appeared first on Intellipaat Blog.

Blog: Intellipaat - Blog

Leave a Comment

Get the BPI Web Feed

Using the HTML code below, you can display this Business Process Incubator page content with the current filter and sorting inside your web site for FREE.

Copy/Paste this code in your website html code:

<iframe src="https://www.businessprocessincubator.com/content/localstorage-in-reactjs/?feed=html" frameborder="0" scrolling="auto" width="100%" height="700">

Customizing your BPI Web Feed

You can click on the Get the BPI Web Feed link on any of our page to create the best possible feed for your site. Here are a few tips to customize your BPI Web Feed.

Customizing the Content Filter
On any page, you can add filter criteria using the MORE FILTERS interface:

Customizing the Content Filter

Customizing the Content Sorting
Clicking on the sorting options will also change the way your BPI Web Feed will be ordered on your site:

Get the BPI Web Feed

Some integration examples

BPMN.org

XPDL.org

×