useSessionStorage
Store, retrieve, and synchronize data from the browser’s session storage with useSessionStorage.
Install:
Note: This hook depends on React’s experimental useEffectEvent.
npm i @uidotdev/usehooks@experimental react@experimental react-dom@experimental
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
Name | Type | Description |
---|---|---|
key | string | The key used to access the session storage value. |
initialValue | any | The initial value to use if there is no item in the session storage with the provided key. |
Return Values
Name | Type | Description |
---|---|---|
localState | any | The current state of the value stored in session storage. |
handleSetState | function | A 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:
import * as React from "react";
import { useSessionStorage } from "@uidotdev/usehooks";
import { cart } from "./icons";
export default function App() {
const [count, setCount] = useSessionStorage("woot", 0);
return (
<section>
<h1>useSessionStorage</h1>
<div>
<button className="link" onClick={() => setCount(0)}>
Clear Cart
</button>
<button
className="link"
onClick={() => {
window.location.reload();
}}
>
Reload Window
</button>
<button
className="link"
onClick={() => {
window.sessionStorage.clear();
window.location.reload();
}}
>
Clear Session
</button>
</div>
<button className="primary" onClick={() => setCount(count + 1)}>
<span>{cart}</span> Add To Cart
</button>
<button className="cart">
<span>{cart}</span>{" "}
<span
key={count}
className={`cart-count ${count > 0 ? "animate" : ""}`}
>
{count}
</span>
</button>
</section>
);
}