简体   繁体   中英

localStorage is not defined in custom hook (Next js)

I have this custom useLocalStorage hook, which works fine with create-react-app, but with Next js it returns undefined in the value init state on line 3.

How can I bypass SSR to always have access to LocalStorage? Or I guess the real question is how do I set state with access to localStorage outside a useEffect?

const useLocalStorage = (storageKey, fallbackState) => {
    const [value, setValue] = useState(
        JSON.parse(localStorage.getItem(storageKey)) ?? fallbackState,
    )

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

    return [value, setValue]
}

This is my implementation of useLocalStorage (I have used it in several projects):

// useLocalStorage.js
import { useEffect, useState } from "react"

export default function useLocalStorage(
    key
    initialValue
) {
    const [value, setValue] = useState(() => {
        if (typeof localStorage !== "undefined") {
            const jsonValue = localStorage.getItem(key)
            if (jsonValue != null) return JSON.parse(jsonValue)
        }

        if (typeof initialValue === "function") {
            return initialValue()
        } else {
            return initialValue
        }
    })

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

    return [value, setValue]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM