Solution

To store an object in localstorage in react js, use localStorage.setItem() with the JSON.stringify() method it will convert an object into a string and store it in localstorage.

localStorage.setItem()

The setItem() method of the Storage interface, when passed a key name and value, will add that key to the given Storage object, or update that key’s value if it already exists.

JSON.stringify()

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Snippet

In this snippet, we will store JSON objects in local storage using localStorage.setItem() with the JSON.stringify() method.

let obj = {
  id: 1,
  name: "John",
  work: "none of your business",
};

// store object in local storage
localStorage.setItem("obj", JSON.stringify(obj));

// Get object from local storage
obj = localStorage.getItem("obj");
if (obj) {
  obj = JSON.parse(obj);
  console.log(obj); // {id: 1, name: 'John', work: 'none of your business}
}

Example

In this example, we will create an object and store it localstorage after storing we will get an object from localstorage and show it in the UI.

Let’s start coding…

import React, { useEffect, useState } from "react";
export default function App() {
  const [obj, setObj] = useState([]);

  useEffect(() => {
    storeLocalstorage();

    fetchLocalstorage();
  }, []);

  const storeLocalstorage = () => {
    let objData = {
      id: 1,
      name: "John",
      work: "none of your business",
    };
    localStorage.setItem("obj", JSON.stringify(objData));
  };

  const fetchLocalstorage = () => {
    let obj = localStorage.getItem("obj");
    if (obj) {
      obj = JSON.parse(obj);
      setObj(obj);
    }
  };

  return (
    <div className="App">
      <h1>{`Object From Localstorage`}</h1>
      <p>{obj.name}</p>
    </div>
  );
}

Output

localStorage, Object

codesandbox