rooks
Version:
Collection of awesome react hooks
83 lines (82 loc) • 2.82 kB
TypeScript
/**
* useSuspenseSessionStorageState
* @description Suspense-enabled hook for sessionStorage state management with cross-tab synchronization
* @see {@link https://rooks.vercel.app/docs/hooks/useSuspenseSessionStorageState}
*/
/**
* Clear cached entry for a specific key - useful for testing
* @internal
* @param key - The sessionStorage key to clear from cache
*/
export declare function clearCache(key?: string): void;
/**
* Control methods interface for the hook
*/
interface UseSuspenseSessionStorageStateControls<T> {
/**
* Get the current value from the hook's state
* @returns The current state value
*/
getItem: () => T;
/**
* Set a new value in sessionStorage and update state
* @param value - The new value to set
*/
setItem: (value: T) => void;
/**
* Delete the item from sessionStorage and reset to initial value
*/
deleteItem: () => void;
}
/**
* Return type for the useSuspenseSessionStorageState hook
*/
type UseSuspenseSessionStorageStateReturnValue<T> = [
T,
UseSuspenseSessionStorageStateControls<T>
];
/**
* Suspense-enabled hook for sessionStorage state management with cross-tab synchronization
*
* This hook will suspend (throw a promise) during initialization to work with React Suspense.
* It provides sessionStorage state management with proper TypeScript generics, JSON serialization,
* error handling, and cross-tab synchronization.
*
* Note: Unlike localStorage, sessionStorage is tab-specific, so cross-tab synchronization
* is primarily for handling storage events within the same tab.
*
* @param key - The sessionStorage key to use
* @param initializer - Function that takes the current sessionStorage value (string | null) and returns the initial state of type T
* @returns Tuple containing [currentValue, controls] where controls has getItem, setItem, and deleteItem methods
*
* @throws {Promise} When data is still loading (for Suspense)
* @throws {Error} When initialization fails
*
* @example
* ```tsx
* function MyComponent() {
* const [count, { setItem, deleteItem }] = useSuspenseSessionStorageState(
* 'my-counter',
* (currentValue) => currentValue ? parseInt(currentValue, 10) : 0
* );
*
* return (
* <div>
* <p>Count: {count}</p>
* <button onClick={() => setItem(count + 1)}>Increment</button>
* <button onClick={deleteItem}>Reset</button>
* </div>
* );
* }
*
* function App() {
* return (
* <Suspense fallback={<div>Loading...</div>}>
* <MyComponent />
* </Suspense>
* );
* }
* ```
*/
declare function useSuspenseSessionStorageState<T>(key: string, initializer: (currentValue: string | null) => T): UseSuspenseSessionStorageStateReturnValue<T>;
export { useSuspenseSessionStorageState };