Solution

To store array in localstorage in react js, use localStorage.setItem() with JSON.stringify() method it will convert array into string and store 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 array in localstorage using localStorage.setItem() with JSON.stringify() method.

let arr = ["aGuideHub", "SortoutCode", "Infinitbility"];

// store array in localstorage
localStorage.setItem("arr", JSON.stringify(arr));

// Get array from localstorage
arr = localStorage.getItem("arr")
if(arr){
  arr = JSON.parse(arr);
  console.log(arr) // ['aGuideHub', 'SortoutCode', 'Infinitbility']
}

Example

In this example, we will create an array and store in localstorage after store we will get array from localstorage and show in th UI.

Let’s start coding…

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

  useEffect(() => {
    storeLocalstorage();

    fetchLocalstorage();
  }, []);

  const storeLocalstorage = () => {
    let arrData = ["aGuideHub", "SortoutCode", "Infinitbility"];
    localStorage.setItem("arr", JSON.stringify(arrData));
  };

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

  return (
    <div className="App">
      <h1>{`Array From Localstorage`}</h1>
      <p>{arr.toString()}</p>
    </div>
  );
}

Output

localStorage, Array

codesandbox