我试图localstorage在 NextJS 中实现钩子,但出现以下错误:Error: Hydration failed because the initial UI does not match what was rendered on the server.。有什么想法可能导致它吗?在我看来,该功能似乎useEffect没有正确使用。如何强制使用 CSR 而不是 SSR 以避免水合错误?
import { useState, useEffect } from 'react';
function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState<T>(() => {
if (typeof window === 'undefined') {
return initialValue;
}
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
useEffect(() => { …Run Code Online (Sandbox Code Playgroud)