Skip to content

useStorageState ​

useStorageState 是一个功能类似于 useState、但会将状态值持久化到浏览器存储中的 React Hook。该值会在页面刷新后保留,并且在配合 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
// Counter with persistent state
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 许可证发布。