useSessionStorage
Get, set and/or remove sessionStorage.
API
interface UseStorageOptions<T> {
defaultValue?: T;
polling?: boolean;
pollingInterval?: number;
compare?: (x: any, y: any) => boolean;
validate?: (value: any) => boolean;
serialize?: (value: T) => string;
deserialize?: (raw: string) => T;
}
function useSessionStorage<T>(
key: string,
options: UseStorageOptions<T> & { defaultValue: T },
): [
value: T,
setSessionStorage: (newValue: T | undefined | ((prevValue: T) => T | undefined)) => void,
];
function useSessionStorage<T>(
key: string,
options?: UseStorageOptions<T>,
): [
value: T | undefined,
setSessionStorage: (
newValue: T | undefined | ((prevValue: T | undefined) => T | undefined),
) => void,
];
Parameters:
key:sessionStoragekey.options: Options object.options.defaultValue: Default value. When set, the returnedvaluetype no longer includesundefined.options.polling: Whether to poll for storage changes. Default isfalse.options.pollingInterval: Polling interval time, in milliseconds. Default is100.options.compare: A function to determine whether the new and old values are equal. Defaults to deep comparison.options.validate: Validate the value got fromsessionStoragewhich is deserialized by thedeserializefunction. If this function returnsfalse, thedefaultValuewill be used.options.serialize: Serialization function. Default isJSON.stringify.options.deserialize: Deserialization function. Default isJSON.parse.
Results:
value: The value parsed by the deserialization function.setSessionStorage: SetsessionStorage. ThenewValuecan also be a function that returns the new value. If it isundefined, the entry will be removed and thedefaultValuewill be returned.
Notes
- Important:
sessionStorageis per-tab — values are not shared across tabs at all. Thestorageevent fires only in other same-origin documents of the same tab (e.g. iframes), never in the document that made the change; enablepolling: trueto sync components in the same page. - The default serialization is
JSON.stringify/JSON.parse:Datebecomes a string,NaNandInfinitybecomenull,Map/Set/circular references are lost, andundefinedarray items becomenull. Useserialize/deserializefor custom types. - In private-browsing or restricted environments, accessing
sessionStoragemay throw; the hook then falls back to in-memory state and writes are not persisted. - Returns
defaultValuein non-browser environments. Thevaluestarts withdefaultValueon the first render and is synchronized with the stored value right after mounting (before the browser paints), so server-rendered and client-hydrated output stay consistent.
Example
The following example sets and removes a value with polling enabled, which keeps the value in sync across hook instances in the same tab.
The value is: default value
import { useSessionStorage } from "@lilib/hooks";
function Example() {
const [value, setSessionStorage] = useSessionStorage("key", {
polling: true,
defaultValue: "default value",
});
return (
<>
<div>
<button onClick={() => setSessionStorage(Math.random().toString())}>
Set random value
</button>{" "}
<button onClick={() => setSessionStorage(undefined)}>Remove</button>
</div>
<div>The value is: {value}</div>
</>
);
}
export default Example;