HooksuseSessionStorage

useSessionStorage()

The useSessionStorage() hook works exactly like useLocalStorage, but persists data only for the duration of the page session. Data is lost when the tab or browser is closed, but survives page reloads and restores.

Import

typescript
import { useSessionStorage } from 'the-react-hooks';

Usage

Data persists on page reload, but is cleared when the tab is closed.

Session NoteActive
0 characters
Component.tsx
import { useSessionStorage } from 'the-react-hooks';

export const Component = () => {
  const [value, setValue] = useSessionStorage('session-key', 'Initial Value');

  return (
    <div>
      <p>Stored Value: {value}</p>
      
      <input
        type="text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
      />
      
      <button onClick={() => setValue('')}>
        Clear
      </button>
    </div>
  );
}

API

Arguments

  • key string The unique key used to store the value in sessionStorage.
  • initialValue T The initial value to use if no value is currently stored in sessionStorage.

Returns

Returns a state tuple similar to useState:
  • [0] value T The current stored value.
  • [1] setValue (value: T | ((val: T) => T)) => void Function to update the state and sessionStorage.