⛄️背景
在开发前端需求时,有时需要在本地缓存记录一些数据状态,再次打开页面时,需要首先查询缓存中的数据,如果有就用缓存中的数据当作初始值,如果对应数据有更新,也要更新缓存
使用场景:
- 新人引导展示的次数
- 页面背景音乐状态,上次离开时是播放还是关闭
- 接口返回的数据,不重要的可以存缓存,加速页面渲染
☃️实现
仿照[state, setState] = useState(initValue)实现一个useCacheState函数
入参为初始状态和缓存的key
[state, setState] = useCacheState(initValue, cacheKey)
import React, { useEffect, useState } from 'react';
import './index.less';
function useCacheState<T>(initValue: T, cacheKey: string) {
const initCacheValue = localStorage.getItem(cacheKey);
const [state, setState] = useState(initCacheValue ?? initValue);
const setCacheState = (payload) => {
updateState();
updateCache();
function updateState() {
setState(payload);
}
function updateCache() {
const newCache = typeof payload === 'function' ? payload(state) : payload;
localStorage.setItem(cacheKey, newCache);
}
};
return [state, setCacheState];
}
⛄️使用❄️
使用方式和useState非常非常类似,只不过有用缓存而已
// 背景音乐静音状态
const [isMuted, setIsMuted] = useCacheState<boolean>(false, CacheKey.IS_MUTED);
写在最后
关注➕我,解锁🔓更多前端技巧
让你成为一个更专业的 前端工程师🤽🏻♀️