Skip to content

useStorageState ​

useStorageState は、useState と同様に動作し、状態の値をブラウザーのストレージに永続化する React フックです。 ページを再読み込みしても値が保持され、localStorage を使う場合はタブ間で共有できます。

インターフェース ​

ts
function useStorageState<T>(
  key: string,
  options?: Object
): readonly [
  state: Serializable<T> | undefined,
  setState: (value: SetStateAction<Serializable<T> | undefined>) => void,
  refreshState: () => void,
];

パラメータ ​

  • keyrequired · string

    ストレージに値を保存するためのキー。

  • optionsObject

    ストレージの動作を設定するオプション。

    • options.storageStorage · localStorage

      ストレージの種類(localStorage または sessionStorage)。デフォルトは localStorage です。

    • options.defaultValueT

      保存済みの値がない場合の初期値。

    • options.serializerFunction

      状態の値を文字列にシリアライズする関数。

    • options.deserializerFunction

      文字列から状態の値をデシリアライズする関数。

戻り値 ​

  • readonly [state: Serializable<T> | undefined, setState: (value: SetStateAction<Serializable<T> | undefined>) => void, refreshState: () => void]

    次の要素を含むタプル。

    • stateSerializable<T> | undefined

      ストレージから取得した現在の状態の値。

    • setState(value: SetStateAction<Serializable<T> | undefined>) => void

      状態を更新し、永続化する関数。

    • refreshState() => void

      ストレージから状態を再取得する関数。

使用例 ​

tsx
// 状態を永続化するカウンター
import { useStorageState } from 'react-simplikit';

function Counter() {
  const [count, setCount] = useStorageState<number>('counter', {
    defaultValue: 0,
  });

  return (
    <button onClick={() => setCount(prev => prev + 1)}>Count: {count}</button>
  );
}

MIT ライセンスの下で配布されています。