PASSWORD RESET

Your destination for complete Tech news

how to store objects in localStorage and sessionStorage in React JS?

1.91K 0
< 1 min read

You can use the localStorage and sessionStorage Web APIs to store objects in React JS. Here’s how you can do it:

Storing Objects in localStorage:

localStorage stores data that persists even after the browser is closed. However, keep in mind that localStorage has limitations on the amount of data you can store (usually around 5-10 MB depending on the browser).

// To set an object in localStorage
const obj = { key: 'value', foo: 'bar' };
localStorage.setItem('myObject', JSON.stringify(obj));

// To get an object from localStorage
const storedObj = JSON.parse(localStorage.getItem('myObject'));

Storing Objects in sessionStorage:

sessionStorage also stores data but only for the duration of a single browser session. It can be useful for storing temporary data that you only need during a user’s current visit.

// To set an object in sessionStorage
const obj = { key: 'value', foo: 'bar' };
sessionStorage.setItem('myObject', JSON.stringify(obj));

// To get an object from sessionStorage
const storedObj = JSON.parse(sessionStorage.getItem('myObject'));

When using these methods in a React component, you might want to wrap the operations in functions or hooks for better organization and reusability:

import React, { useState } from 'react';

function App() {
  const [storedObj, setStoredObj] = useState(JSON.parse(localStorage.getItem('myObject')) || {});

  const saveToLocalStorage = (data) => {
    localStorage.setItem('myObject', JSON.stringify(data));
    setStoredObj(data);
  };

  const clearLocalStorage = () => {
    localStorage.removeItem('myObject');
    setStoredObj({});
  };

  return (
    <div>
      <button onClick={() => saveToLocalStorage({ key: 'new value', foo: 'new bar' })}>Save to Local Storage</button>
      <button onClick={clearLocalStorage}>Clear Local Storage</button>
      <p>Stored Object: {JSON.stringify(storedObj)}</p>
    </div>
  );
}

export default App;

Remember to use JSON.stringify() to convert your object to a JSON string before storing, and JSON.parse() to convert it back to an object when retrieving from storage. Also, be cautious with storing sensitive or large amounts of data in these storage mechanisms.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.