Skip to content

Storage

@granit/storage provides a typed storage factory for localStorage and sessionStorage with automatic dd: key prefixing and custom serialization. @granit/react-storage wraps this into a useStorage hook that synchronizes component state with the browser storage via useSyncExternalStore, including cross-tab updates.

Peer dependencies: react ^19

  • Directory@granit/storage/ TypedStorage factory with key prefixing (framework-agnostic)
    • @granit/react-storage useStorage hook with cross-tab sync
PackageRoleDepends on
@granit/storagecreateStorage, TypedStorage, StorageOptions
@granit/react-storageuseStorage hook@granit/storage, react
import { useStorage } from '@granit/react-storage';
function Sidebar() {
const [open, setOpen] = useStorage('sidebar-open', false);
return <nav data-open={open}>...</nav>;
}
interface StorageOptions<T> {
serialize?: (value: T) => string; // default: JSON.stringify
deserialize?: (raw: string) => T; // default: JSON.parse
storage?: 'local' | 'session'; // default: 'local'
}
interface TypedStorage<T> {
get(): T | null;
set(value: T): void;
remove(): void;
readonly key: string; // prefixed key (e.g. "dd:theme")
}

Creates a typed storage accessor. All keys are automatically prefixed with dd: to avoid collisions with third-party libraries.

function createStorage<T>(key: string, options?: StorageOptions<T>): TypedStorage<T>;

useStorage<T>(key, defaultValue, options?)

Section titled “useStorage<T>(key, defaultValue, options?)”

React hook that synchronizes component state with browser storage.

function useStorage<T>(
key: string,
defaultValue: T,
options?: StorageOptions<T>
): [T, (value: T) => void];
  • Uses useSyncExternalStore for tear-free reads
  • Cross-tab synchronization via the native storage event
  • Maintains referential stability through internal caching
  • Keys are automatically prefixed with dd:

All keys are prefixed with dd: (Digital Dynamics) to avoid collisions:

Input keyActual storage key
themedd:theme
sidebar-opendd:sidebar-open
localedd:locale
CategoryKey exportsPackage
TypesTypedStorage<T>, StorageOptions<T>@granit/storage
FactorycreateStorage()@granit/storage
React hookuseStorage()@granit/react-storage