LocalStorage in ReactJS


In this article, we are going to see how to set and retrieve data in the localStorage memory of the user’s browser in a React application.

LocalStorage is a web storage object to store the data on the user’s computer locally, which means the stored data is saved across browser sessions and the data stored has no expiration time.

Syntax

// To store data
localStorage.setItem('Name', 'Rahul');

// To retrieve data
localStorage.getItem('Name');

// To clear a specific item
localStorage.removeItem('Name');

// To clear the whole data stored in localStorage
localStorage.clear();

Set, retrieve and remove data in localStorage

In this example, we will build a React application which takes the username and password from the user and stores it as an item in the localStorage of the user’s computer.

Example

App.jsx

import React, { useState } from 'react';

const App = () => {

   const [name, setName] = useState('');
   const [pwd, setPwd] = useState('');

   const handle = () => {
      localStorage.setItem('Name', name);
      localStorage.setItem('Password', pwd);
   };
   const remove = () => {
      localStorage.removeItem('Name');
      localStorage.removeItem('Password');
   };
   return (
      <div className="App">
         <h1>Name of the user:</h1>
         <input
            placeholder="Name"
            value={name}
            onChange={(e) => setName(e.target.value)}
         />
         <h1>Password of the user:</h1>
         <input
            type="password"
            placeholder="Password"
            value={pwd}
            onChange={(e) => setPwd(e.target.value)}
         />
         <div>
            <button onClick={handle}>Done</button>
         </div>
         {localStorage.getItem('Name') && (
            <div>
               Name: <p>{localStorage.getItem('Name')}</p>
            </div>
         )}
         {localStorage.getItem('Password') && (
            <div>
               Password: <p>{localStorage.getItem('Password')}</p>
            </div>
         )}
         <div>
            <button onClick={remove}>Remove</button>
         </div>
      </div>
   );
};
export default App;

In the above example, when the Done button is clicked, the handle function is executed which will set the items in the localStorage of the user and display it. But when the Remove button is clicked, the remove function is executed which will remove the items from the localStorage.

Output

This will produce the following result.

Updated on: 01-Nov-2023

30K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements