i’m fairly new to React
What i’m trying to achieve here is to is to make a custom hook and store data into localStorage but my hook doesn’t seem to be working
here’s the hook useLocalStorage
import { useState, useEffect } from 'react'
// import FeedbackData from '../data/FeedbackData'
export function useLocalStorage(key, initialValue) {
const [localValue, setLocalValue] = useState(() => {
const storedValue = localStorage.getItem(key)
if (storedValue !== undefined || storedValue !== null) {
return storedValue
} else {
return ''
}
})
useEffect(() => {
localStorage.setItem(key, JSON.stringify(localValue))
}, [localValue])
return [localValue, setLocalValue]
}
here’s how i’m using it in my context provider
const [feedback, setFeedback] = useLocalStorage('tasks', '')
2
Answers
Try to use this:
You should not check
storedValue
forundefined
because localStorage returnsnull
if the key does not exist. Also, you must addkey
to the dependencies array ofuseEffect
hook.And I think you might have forgotten to use
JSON.parse()
because localeStorage usually stores JSON data.Try this:
In this updated version, if
storedValue
is notnull
, it will be parsed usingJSON.parse()
. Otherwise, theinitialValue
passed to the hook will be used as the default value.