Skip to content

useStorage ​

Hook that manages storage value

browser
test coverage
Last changed: 9 days ago

Installation ​

Library
CLI
Manual
typescript
import { useStorage } from '@siberiacancode/reactuse';

Usage ​

typescript
const { value, set, remove } = useStorage('key', 'value');

Demo ​

Api ​

Parameters

NameTypeDefaultNote
keystring-The key of the storage
initialValue?UseStorageInitialValue<Value>-The initial value of the storage

Returns

UseStorageReturn<Value>

Parameters

NameTypeDefaultNote
keystring-The key of the storage
params.serializer?(value: Value) => string-The serializer function
params.deserializer?(value: string) => Value-The deserializer function
params.storage?Storage-The storage
params.initialValue?UseStorageInitialValue<Value>-The initial value of the storage

Returns

UseStorageReturn<Value>

Type declaration ​

typescript
export type UseStorageInitialValue<Value> = (() => Value) | Value;

export interface UseStorageOptions<Value> {
  /* The initial value of the storage */
  initialValue?: UseStorageInitialValue<Value>;
  /* The storage to be used */
  storage?: Storage;
  /* The deserializer function to be invoked */
  deserializer?: (value: string) => Value;
  /* The serializer function to be invoked */
  serializer?: (value: Value) => string;
}

export interface UseStorageReturn<Value> {
  /* The value of the storage */
  value: Value;
  /* The error state of the storage */
  remove: () => void;
  /* The loading state of the storage */
  set: (value: Value) => void;
}

export interface UseStorage {
  <Value>(
    key: string,
    options: UseStorageOptions<Value> & { initialValue: UseStorageInitialValue<Value> }
  ): UseStorageReturn<Value>;

  <Value>(key: string, options?: UseStorageOptions<Value>): UseStorageReturn<Value | undefined>;

  <Value>(key: string, initialValue: UseStorageInitialValue<Value>): UseStorageReturn<Value>;

  <Value>(key: string): UseStorageReturn<Value | undefined>;
}

Source ​

Source • Demo

Contributors ​

B
babin
babin
D
debabin
debabin

Released under the MIT License.