Rehooks
Content

useSessionStorage

A React hook that allows you to persist data across browser sessions.

useSessionStorage

Usage

Component.tsx
import { useSessionStorage } from "~/hooks/useSessionStorage";
import React from "react";
 
function Component() {
  const [name, setName] = useSessionStorage("name", "John Doe");
 
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };
 
  return (
    <div>
      <h2>Session Storage Demo</h2>
      <input
        type="text"
        value={name}
        onChange={handleChange}
        placeholder="Enter your name"
      />
      <p>Your name is: {name}</p>
    </div>
  );
}

API

useSessionStorage

function useSessionStorage<T>(
  key: string,
  initialValue: T,
): [T, (value: T) => void];

Parameters

NameTypeDescription
keystringThe key of the item to be stored in session storage.
initialValueTThe initial value to be used if the item does not exist in session storage.

Returns

NameTypeDescription
valueTThe value of the item in session storage.
setValue(value: T) => voidA function that sets the value of the item in session storage.

On this page