Storage
/ API Reference
Storage
/ API Reference

useStorage

A React hook to manage a value in a storage.
Unless you need to use a custom storage, it is recommended to use the specialized hooks (useLocalStorage, useSessionStorage, useIndexedStorage) instead.

The Gist

import { useStorage, T_SyntheticStorage } from '@weser/storage'
import cache from './cache'

const getStorage = (): T_SyntheticStorage => ({
  getItem: cache.get,
  setItem: cache.set,
})

function Component() {
  const [counter, setCounter, isLoading] = useStorage(getStorage, 'counter', 0)

  if (isLoading) {
    return <div>Loading...</div>
  }

  return (
    <div>
      {counter}
      <button onClick={() => setCounter(counter + 1)}>Increment</button>
      <button onClick={() => setCounter(counter - 1)}>Decrement</button>
    </div>
  )
}

Parameters

ParameterTypeDescription
getStorage() => T_SyntheticStorageThe function to get the storage.
keystringThe key to store the value under.
initialStateTThe initial value to store.
configConfigThe configuration object.

Config

ParameterTypeDefaultDescription
onHydrated(value?: T) => voidA callback function that is called when the value is hydrated. This is invoked at the same time the loading flag is set to false.
encode(value: T) => anyJSON.stringify (new tab)A custom encoder function to encode the value.
decode(value: any) => TJSON.parse (new tab)A custom decoder function to decode the value.

Example

const [counter, setCounter, isLoading] = useStorage(getStorage, 'counter', 0, {
  onHydrated: (value) => {
    console.log('Value hydrated:', value)
  },
  encode: (value) => value.toString(),
  decode: (value) => Number(value),
})

Returns

([T, Dispatch<SetStateAction<T>>, boolean]) A tuple where the first element is the value, the second element is a function to update the value and the third element is a boolean indicating if the value is still loading.

Generic Type

By default, all storage hooks infer the type from the initial state.
However, when working with objects or arrays, you may want to specify the type explicitly.

type Account = {
  id: string
  name: string
  email: string
  password: string
}

const [counter, setCounter, isLoading] = useStorage<Account | null>(
  getStorage,
  'account',
  null
)
On this page