UNPKG

reactuals

Version:

A useful package providing a collection of 50+ React hooks and utilities to simplify React development.

30 lines (29 loc) 826 B
import { useState } from "react"; /** * A hook that synchronizes state with sessionStorage. * * Example: * const [sessionData, setSessionData] = useSessionStorage("data", {}); */ export function useSessionStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = window.sessionStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.warn(error); return initialValue; } }); const setValue = (value) => { try { setStoredValue(value); window.sessionStorage.setItem(key, JSON.stringify(value)); } catch (error) { console.warn(error); } }; return [storedValue, setValue]; }