useSessionStorage

Store, retrieve, and synchronize data from the browser’s session storage with useSessionStorage.

Install:

npm i @uidotdev/usehooks

Description:

The useSessionStorage hook allows you to store and retrieve data in the browser’s session storage, providing a way to persist data across multiple page views or browser refreshes. The hook utilizes the window.sessionStorage API to store and retrieve data in the session storage. It automatically synchronizes the stored data with the local state of the component using the hook. Additionally, it listens for changes in the session storage and updates the local state accordingly, ensuring that the component reflects the latest stored values.

Parameters

NameTypeDescription
keystringThe key used to access the session storage value.
initialValueanyThe initial value to use if there is no item in the session storage with the provided key.

Return Values

NameTypeDescription
localStateanyThe current state of the value stored in session storage.
handleSetStatefunctionA function to set the state of the value in the session storage. This function accepts a new value or a function that returns a new value. The value is also saved in the session storage under the provided key.

Demo:

Example:

More Hooks:

Sort: