用于在 localStorage / sessionStorage 中存储数据,并支持可选过期时间和跨标签页同步的 Hook。
import { useStorage } from '@resin-hooks/core';| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| options | UseStorageOptions<T> |
必填 | 存储配置 |
| key | string |
- | 存储使用的 key,建议在项目内保持唯一 |
| expire | number | null |
null |
过期时间(毫秒),null 表示不过期 |
| type | 'local' | 'session' |
'local' |
使用 localStorage 还是 sessionStorage |
| defaultValue | T |
undefined |
没有存储值时返回的默认值 |
返回一个三元组:
T \| undefined):当前存储中的值(可能为默认值或未初始化)(value: T, expire?: number \| null) => void):写入存储并更新状态,可传入自定义过期时间覆盖默认 expire() => void):删除存储,并将状态重置为 defaultValueuseStorage 内部监听了浏览器的 storage 事件:
key 的值在其他标签页被修改或删除时,当前页面的状态会自动更新defaultValue这非常适合以下场景:
sessionStorage)window.localStorage / window.sessionStorage,SSR 环境请在客户端渲染阶段使用JSON.stringify / JSON.parse,请确保传入的值可被序列化expire 和 setValue 第二个参数都以毫秒为单位useStorage 使用