UNPKG

@tanstack/react-persister

Version:

Utilities for persisting state to local storage, session storage, indexedDB, and more.

33 lines (32 loc) 948 B
import { useState, useEffect } from "react"; import { useStoragePersister } from "./useStoragePersister.js"; function useStorageState(initialValue, options) { const persister = useStoragePersister(options); const [state, setState] = useState(initialValue); useEffect(() => { setState(persister.loadState() ?? initialValue); }, []); useEffect(() => { persister.saveState(state); }, [state]); return [state, setState]; } function useLocalStorageState(key, initialValue, options) { return useStorageState(initialValue, { ...options, key, storage: typeof window !== "undefined" ? localStorage : null }); } function useSessionStorageState(key, initialValue, options) { return useStorageState(initialValue, { ...options, key, storage: typeof window !== "undefined" ? sessionStorage : null }); } export { useLocalStorageState, useSessionStorageState }; //# sourceMappingURL=useStorageState.js.map