498

useStorage

Hook that manages storage value

statehightest coverage
Auto-saveAutomatically save your changes as you work
import { useStorage } from '@siberiacancode/reactuse';
import { SaveIcon } from 'lucide-react';

const Demo = () => {
  const autoSaveStorage = useStorage('reactuse-demo-autosave', true);

  return (
    <section className='border-border flex w-full max-w-sm min-w-0 flex-col gap-2 rounded-xl border p-2 md:max-w-md'>
      <div className='flex w-full min-w-0 items-center justify-between gap-4 p-4'>
        <div className='flex min-w-0 items-center gap-3'>
          <SaveIcon className='text-muted-foreground size-6 shrink-0' />
          <div className='flex min-w-0 flex-col gap-0.5'>
            <span className='text-sm font-medium'>Auto-save</span>
            <span className='text-muted-foreground text-xs break-words'>
              Automatically save your changes as you work
            </span>
          </div>
        </div>

        <input
          checked={autoSaveStorage.value}
          role='switch'
          type='checkbox'
          onChange={(event) => autoSaveStorage.set(event.target.checked)}
        />
      </div>
    </section>
  );
};

export default Demo;

Installation

pnpm add @siberiacancode/reactuse

Usage

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

Type Declarations

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>): UseStorageReturn<Value | undefined>;

  <Value>(
    key: string,
    initialValue?: UseStorageInitialValue<Value>
  ): UseStorageReturn<Value | undefined>;
}

API

Parameters

NameTypeDefaultNote
keystring-The key of the storage
initialValueUseStorageInitialValue<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.storageStorage-The storage
params.initialValueUseStorageInitialValue<Value>-The initial value of the storage

Returns

UseStorageReturn<Value>

Contributors

ddebabinbbabin

Last updated on