Solution

To store array in sessionstorage in react js, use sessionStorage.setItem() with JSON.stringify() method it will convert array into string and store in sessionstorage.

sessionStorage.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 sessionstorage using sessionStorage.setItem() with JSON.stringify() method.

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

// store array in sessionstorage
sessionStorage.setItem("arr", JSON.stringify(arr));

// Get array from sessionstorage
arr = sessionStorage.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 sessionstorage after store we will get array from sessionstorage and show in th UI.

Let’s start coding…

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

  useEffect(() => {
    storeSessionstorage();

    fetchSessionstorage();
  }, []);

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

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

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

Output

sessionStorage, Array

codesandbox