我创建了一个名为useLocalStorage的自定义Next.js钩子来持久化本地存储中的数据。它工作正常,就像当尝试更新数据时,本地存储也在更新,但本地存储内存在每次渲染时都会刷新。我如何防止这种行为?
import { SetStateAction, useEffect, useRef, useState } from "react";
function useLocalStorage(
key: string,
initialState: string
): [state: string, setState: React.Dispatch<SetStateAction<string>>] {
const [state, setState] = useState<string>(initialState || "");
useEffect(() => {
let savedValue = localStorage.getItem(key);
if (savedValue) {
return setState(JSON.parse(savedValue));
}
}, []);
useEffect(() => {
localStorage.setItem(key, JSON.stringify(state));
}, [state]);
return [state, setState];
}
export default useLocalStorage;
1条答案
按热度按时间neekobn81#
这可能是由于第一个
useEffect
挂接中的return语句。在
useEffect
回调内返回用于清理,如文档中所述:https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup