Local storage in React JS is a powerful tool for persisting data on the client side across sessions. It allows web applications to store data locally within the user’s browser, making it accessible even after the browser is closed and reopened. This article will guide you through the essentials of using local storage in React applications, including saving, retrieving, and removing data.

Understanding Local Storage

Unlike cookies, local storage is not sent to the server with every request, and it can store more data (up to 5MB). Data stored in local storage is accessible across browser sessions until explicitly cleared.

Difference Between Local Storage and Session Storage in React

Understanding these differences is crucial when deciding which storage solution best fits your application’s needs.

Local Storage

  • Persistence: Data stored in local storage does not expire and remains available across browser sessions until explicitly removed by the application or the user. This makes it an excellent choice for storing data that needs to persist beyond the current session, such as user preferences or application settings.
  • Capacity: Typically, local storage offers up to 5MB of storage space, although this can vary by browser.
  • Accessibility: Data stored in local storage is accessible across all tabs and windows within the same origin (protocol, domain, and port).

Session Storage

  • Persistence: Unlike local storage, session storage is designed for data that only needs to persist for the duration of the page session. A session lasts as long as the browser is open and survives over page reloads and restores. However, opening a page in a new tab or window will cause a new session to be initiated, which means session storage is not shared across tabs and windows.
  • Capacity: Session storage also typically offers up to 5MB of space, similar to local storage.
  • Use Cases: Session storage is ideal for data that should not persist between sessions, such as temporary application state or form data in multi-step processes.

Guiding Steps for Integration of Local Storage in React

Saving Data to Local Storage in React

To save data to local storage, you can use the setItem method, which takes two arguments: the key and the value. Since local storage can only store strings, objects must be stringified using JSON.stringify before storing.

const user = { name: "John Doe", age: 30 };
localStorage.setItem('user', JSON.stringify(user));

Retrieving Data from Local Storage

Data can be retrieved from local storage using the getItem method with the key. Since data is stored as a string, you’ll often need to parse it back into JavaScript objects or other formats using JSON.parse.

const user = JSON.parse(localStorage.getItem('user'));
console.log(user.name); // Output: John Doe

Removing Data from Local Storage

To remove data from local storage, you can use the removeItem method with the key. To clear all local storage data for your domain, use localStorage.clear().

localStorage.removeItem('user'); // Removes the specific item
localStorage.clear(); // Clears all local storage

Using Local Storage in React Components

React components can interact with local storage within their lifecycle methods or hooks. For example, you can save data when a component unmounts or retrieve data when it mounts.

Class Component Example

class UserProfile extends React.Component {
  componentDidMount() {
    const user = JSON.parse(localStorage.getItem('user'));
    // Set state or perform actions with user data
  }

  componentWillUnmount() {
    // Save data to local storage before unmounting
    localStorage.setItem('user', JSON.stringify(this.state.user));
  }

  // Rest of the component
}

Functional Component Example with Hooks

import React, { useState, useEffect } from 'react';

function UserProfile() {
  const [user, setUser] = useState({});

  useEffect(() => {
    const storedUser = JSON.parse(localStorage.getItem('user'));
    if (storedUser) {
      setUser(storedUser);
    }

    // Save to local storage on component unmount
    return () => {
      localStorage.setItem('user', JSON.stringify(user));
    };
  }, [user]);

  // Rest of the component
}

How to Store Files in Local Storage in React JS

You can encode files into strings using Base64 encoding and then store those strings in local storage. It’s important to note that due to the size limit of local storage (5MB on most browsers), this method is only feasible for small files.

Example of File Storage and Retrieving in React

Here is a React component that demonstrates this process:

File Storage 

import React, { useState } from 'react';

function FileStorageComponent() {
    const [selectedFile, setSelectedFile] = useState();

    const handleFileChange = (event) => {
        setSelectedFile(event.target.files[0]);
    };

    const saveFileToLocalStorage = () => {
        const reader = new FileReader();
        reader.readAsDataURL(selectedFile);
        reader.onload = () => {
            const base64String = reader.result;
            localStorage.setItem('storedFile', base64String);
            alert('File stored in local storage.');
        };
        reader.onerror = (error) => {
            console.log('Error: ', error);
        };
    };

    return (
        <div>
            <input type="file" onChange={handleFileChange} />
            <button onClick={saveFileToLocalStorage}>Save to Local Storage</button>
        </div>
    );
}

export default FileStorageComponent;

File Retrieving 

To retrieve and use the stored file (e.g., displaying an image), fetch the Base64-encoded string from local storage and use it as the source for an <img> tag or process it according to the file type.

function DisplayStoredFile() {
    const fileSrc = localStorage.getItem('storedFile');

    return fileSrc ? <img src={fileSrc} alt="Stored" /> : <p>No file stored.</p>;
}

Important Considerations

  • Storage Limit: Be mindful of the 5MB storage limit. Base64 encoding increases the size of the file by approximately 33%, so this method is suitable only for small files.
  • Performance: Storing large files can impact the performance of your application. Retrieval and decoding of large Base64 strings can be CPU-intensive and lead to noticeable delays.
  • Security: Local storage is accessible to any scripts running on your page. Avoid storing sensitive or private files using this method.

Conclusion

Local storage is a simple yet effective way to persist data in your React applications. By leveraging the Web Storage API, you can enhance the user experience by retaining user preferences, saving application state across sessions, and more. Remember, since local storage is accessible through JavaScript on the client side, it should not be used to store sensitive information.

This overview provides a foundational understanding of working with local storage in React JS, offering a starting point for developers to implement persistent client-side data storage solutions effectively.

Local Storage -FAQs

Can we use local storage in React JS?

Yes, local storage can be used in React JS to store and retrieve data persistently within the browser.

How to use local storage in React JS?

To use local storage in React JS, you can use the localStorage object provided by the browser, allowing you to store key-value pairs persistently within the user’s browser.

Can local storage in React JS handle large amounts of data efficiently?

Local storage in React JS is suitable for small to moderate amounts of data. While it can handle larger data sets, performance may degrade with excessive data due to its synchronous nature and storage limitations.

Does local storage in React JS work in private browsing mode?

Local storage in React JS does not persist data in private browsing mode as it relies on browser storage, which is disabled in such modes. However, session storage can be used as an alternative for temporary data storage in these scenarios.

Can data stored in local storage be accessed by other websites or browser extensions?

Data stored in local storage in React JS is accessible only to the same origin (website) that stored it. It cannot be accessed by other websites or browser extensions due to the same-origin policy enforced by web browsers.

Newsletter

I am a Software developer

My name is muhammad adnan and i am a professtional software developer. specialize in designing and developing efficient software applications.

Check out My Portfolio