rooks
Version:
Collection of awesome react hooks
80 lines (79 loc) • 2.62 kB
TypeScript
/**
* useSuspenseLocalStorageState
* @description Suspense-enabled hook for localStorage state management with cross-tab synchronization
* @see {@link https://rooks.vercel.app/docs/hooks/useSuspenseLocalStorageState}
*/
/**
* Clear cached entry for a specific key - useful for testing
* @internal
* @param key - The localStorage key to clear from cache
*/
export declare function clearCache(key?: string): void;
/**
* Control methods interface for the hook
*/
interface UseSuspenseLocalStorageStateControls<T> {
/**
* Get the current value from the hook's state
* @returns The current state value
*/
getItem: () => T;
/**
* Set a new value in localStorage and update state
* @param value - The new value to set
*/
setItem: (value: T) => void;
/**
* Delete the item from localStorage and reset to initial value
*/
deleteItem: () => void;
}
/**
* Return type for the useSuspenseLocalStorageState hook
*/
type UseSuspenseLocalStorageStateReturnValue<T> = [
T,
UseSuspenseLocalStorageStateControls<T>
];
/**
* Suspense-enabled hook for localStorage state management with cross-tab synchronization
*
* This hook will suspend (throw a promise) during initialization to work with React Suspense.
* It provides localStorage state management with proper TypeScript generics, JSON serialization,
* error handling, and cross-tab synchronization.
*
* @param key - The localStorage key to use
* @param initializer - Function that takes the current localStorage 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 }] = useSuspenseLocalStorageState(
* '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 useSuspenseLocalStorageState<T>(key: string, initializer: (currentValue: string | null) => T): UseSuspenseLocalStorageStateReturnValue<T>;
export { useSuspenseLocalStorageState };