A2oz

How Do I Remove Data From Session Storage in React?

Published in React 2 mins read

You can remove data from session storage in React using the sessionStorage.removeItem() method.

Removing Specific Data

To remove a specific item from session storage, use the sessionStorage.removeItem() method, passing the key of the data you want to remove as an argument.

sessionStorage.removeItem('user_name');

This code will remove the data associated with the key user_name from session storage.

Clearing All Session Storage Data

To remove all data from session storage, use the sessionStorage.clear() method.

sessionStorage.clear();

This will remove all data stored in session storage.

Example

Here's an example of how to remove data from session storage in a React component:

import React, { useState } from 'react';

function MyComponent() {
  const [userName, setUserName] = useState('');

  const handleRemoveData = () => {
    sessionStorage.removeItem('user_name');
    setUserName('');
  };

  return (
    <div>
      <input
        type="text"
        value={userName}
        onChange={(e) => setUserName(e.target.value)}
      />
      <button onClick={handleRemoveData}>Remove Data</button>
    </div>
  );
}

export default MyComponent;

This code will remove the data associated with the key user_name from session storage when the "Remove Data" button is clicked.

Practical Insights

  • Data Removal: Remember that removing data from session storage is a permanent operation. Once removed, the data is lost.
  • State Management: When removing data from session storage, consider updating your component state to reflect the changes. This ensures your UI stays in sync with the data stored in session storage.

Related Articles