devugur

Exploring the Utility of Session Storage: Ideal Use Cases

10 Dec 2023

Photo by <a target='_blank' href="https://unsplash.com/@awcreativeut?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Adam Winger</a> on <a target='_blank' href="https://unsplash.com/photos/a-storage-building-with-red-doors-and-a-sky-background-OpV94f2edwE?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a>
Photo by Adam Winger on Unsplash

Exploring the Utility of Session Storage: Ideal Use Cases

It is a web storage mechanism and it may be handy in some cases.

Scope

Data stored in sessionStorage is limited to the duration of a page session. It is not persistent like cookies or local storage, which means that the data will be lost when the user closes the browser tab or navigates away from the page.

Storage Limit

According to MDN sessionStorage can hold 5 MIB of data per origin/page.

Storage usage can be checked via navigator.storage.estimate() but it is an estimate not the actual value.

Key-Value Pairs

Data is stored in key-value fashion. Here are the methods you can use to interact with the sessionStorage:

  • sessionStorage.setItem('name','ugur')
  • sessionStorage.getItem('name')
  • sessionStorage.removeItem('name')
  • sessionStorage.clear()

When to use sessionStorage instead of localStorage?

If you want to store data that should persist beyond the current session, across browser tabs, and even when the user returns to the website at a later time, you better use localStorage.

If you maintain some data in the current session and it is okay to flush that data after closing the tab, use sessionStorage. Multi-step form would be a great use case for sessionStorage.

Examples with React

You can use sessionStorage with a custom hook. Check this out:

function useSessionStorage<T>(key: string, initialValue: T) {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      // Attempt to get the item from sessionStorage
      const item = sessionStorage.getItem(key);
      // If the item exists, parse and return it
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If there's an error, return the initialValue
      console.error('Error retrieving data from sessionStorage:', error);
      return initialValue;
    }
  });

  // Update sessionStorage whenever storedValue changes
  useEffect(() => {
    try {
      // Stringify the value and store it in sessionStorage
      sessionStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error('Error storing data in sessionStorage:', error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue] as const;
}

export default useSessionStorage;

Note that we are storing the data as a string with the help of JSON.stringify method since sessionStorage supports only string values. When we retrieve the value, we need to parse it back.

And this is the use case in the component:

import React from 'react';
import useSessionStorage from './useSessionStorage';

function MyComponent() {
  const [data, setData] = useSessionStorage<SessionStorageData>('myData', {
    name: 'ugur',
    age: 28,
  });

  return (
    <div>
      <p>Data from sessionStorage: {JSON.stringify(data)}</p>
      <button onClick={() => setData({ name: 'messi', age: 35 })}>Update Data</button>
    </div>
  );
}

export default MyComponent;

Small but important notes

  • if there is not item in the store with the given key, getItem(key) will return null.
  • if you store undefined as a value to the store, it will be stored as 'undefined' string. When you retrieve it back, you will get as string, so it is not falsy.