-
Notifications
You must be signed in to change notification settings - Fork 0
useSessionStorage
Synchronize a React state variable directly with the browser's sessionStorage. Data persists perfectly across hot-reloads and page refreshes, but is completely cleared when the browser tab or window is closed. It automatically handles JSON.parse and JSON.stringify under the hood.
A simple string value synced to sessionStorage.
import { useSessionStorage } from "react-hook-lab";
function DraftForm() {
const [draft, setDraft] = useSessionStorage("draft_text", "");
return (
<div>
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
placeholder="Type here... it survives reloads!"
/>
<button onClick={() => setDraft("")}>Clear</button>
</div>
);
}Syncing complex objects or arrays. The hook automatically handles the JSON serialization and parsing for you safely.
import { useSessionStorage } from "react-hook-lab";
interface UserPrefs {
volume: number;
showSubtitles: boolean;
}
function VideoPlayer() {
const [prefs, setPrefs] = useSessionStorage<UserPrefs>("video_prefs", {
volume: 50,
showSubtitles: false
});
return (
<div>
<button onClick={() => setPrefs({ ...prefs, showSubtitles: !prefs.showSubtitles })}>
Subtitles: {prefs.showSubtitles ? "ON" : "OFF"}
</button>
</div>
);
}Using standard useState functional updates to derive the next state from the previous state.
import { useSessionStorage } from "react-hook-lab";
function Counter() {
const [count, setCount] = useSessionStorage("session_counter", 0);
const increment = () => {
// You can pass a callback just like standard useState!
setCount((prev) => prev + 1);
};
return <button onClick={increment}>Count: {count}</button>;
}-
key- Type:
string - Description: The unique string key used to store the data inside
window.sessionStorage.
- Type:
-
initialValue- Type:
T - Description: The fallback value returned if the key does not exist in storage (or during Server Side Rendering).
- Type:
Returns a standard React state tuple:
-
value(T): The current state, read from sessionStorage (or the initialValue). -
setStoredValue((newValue: T | ((prev: T) => T)) => void): A setter function that updates both the React state and the browser'ssessionStoragesimultaneously.
On the initial render, useSessionStorage attempts to read the specified key from the browser. If it exists, it safely attempts a JSON.parse(). If parsing fails or the key doesn't exist, it falls back to the initialValue.
When setStoredValue is invoked, it updates the internal React useState (triggering a re-render) while synchronously writing the JSON.stringify() version of your payload back into the window.sessionStorage. The hook is fully SSR-safe by guarding window checks, ensuring it gracefully falls back to initialValue when executed on the server.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM