PASSWORD RESET

Your destination for complete Tech news

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

2.9K 0
< 1 min read

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

Storing Objects in localStorage:

LocalStorage stores data that should also persist after the browser is closed. Keep in mind that the downside is, of course, its limit in storing data up to 5-10MB 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.