Home > Net >  Why useLocalStorage does not work with Next.js?
Why useLocalStorage does not work with Next.js?

Time:12-03

This will raise an Error: Hydration failed because the initial UI does not match what was rendered on the server. error:

const [selectedOrganizationShortId, setSelectedOrganizationShortId] =
useLocalStorage<string>('teamId', undefined)

This will not:

const [selectedOrganizationShortId, setSelectedOrganizationShortId] =
useState<string>(undefined)
const [selectedProgramId, saveSelectedProgramId] = useState<
string | undefined
>(undefined)

though both does the same. I would use useLocalStorage as it is handy convenience solution, but seems it is not compatible with Next.js.

useLocalStorage is used from here: https://usehooks-ts.com/react-hook/use-local-storage

CodePudding user response:

My answer is a suggestion for your need.

You could write a custom hook for your purpose so no need to any external libraries:

export function useLocalStorage<T>(key: string, fallbackValue: T) {
    const [value, setValue] = useState(fallbackValue);
    useEffect(() => {
        const stored = localStorage.getItem(key);
        setValue(stored ? JSON.parse(stored) : fallbackValue);
    }, [fallbackValue, key]);

    useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
    }, [key, value]);

    return [value, setValue] as const;
}
  • Related