@reactivers/hooks Github link@reactivers/hooks NPM link

useLocalStorage

Introduction

  • useLocalStorage makes local storage management easier for you.
  • It allows you keep your local storages in state optionally.
  • All your components can access and listen local storages easily.
const { getItem, setItem } = useLocalStorage("test-value");

Getting Started

  • You need to import useLocalStorage and LocalStorageProvider.
  • useLocalStorage reads data from LocalStorageProvider. So you need to wrap your entry component with LocalStorageProvider.

From Collection

import { useLocalStorage, LocalStorageProvider } from "@reactivers/hooks";

From Package

import { useLocalStorage, LocalStorageProvider } from "@reactivers/use-local-storage";

Interfaces

Provider

interface LocalStorageProviderProps {
    // If passed False it doesn't store the data in state.
    withState?: boolean; // Default = True

    // Calls this on any change in localStorage via useLocalStorage.
    onChange?: (localStorage: Record<string, any>) => void;
}

Hook


interface IUseLocalStorage {
  // If key passed, it controls and gets only the given key name.
  // Otherwise you can access all local storage.
  key?: string
}

interface IUseLocalStorageReturn {
    localStorage: Record<string, any>;
    getItem: (key?: string) => any;
    setItem: (value: any) => void;
    setItemWithKey: (key: string, value: any) => void;
    removeItem: (key?: string) => void;
}

Example

Example Preview - CodeSandbox