skip to Main Content

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


  1. Try to use this:

    import { useState, useEffect } from 'react'
    
    export function useLocalStorage(key, initialValue) {
      const [localValue, setLocalValue] = useState(() => {
        const storedValue = localStorage.getItem(key)
        return storedValue !== null ? storedValue : initialValue
      })
    
      useEffect(() => {
        localStorage.setItem(key, JSON.stringify(localValue))
      }, [key, localValue])
    
      return [localValue, setLocalValue]
    }
    

    You should not check storedValue for undefined because localStorage returns null if the key does not exist. Also, you must add key to the dependencies array of useEffect hook.

    And I think you might have forgotten to use JSON.parse() because localeStorage usually stores JSON data.

    Login or Signup to reply.
  2. Try this:

    import { useState, useEffect } from 'react';
    
    export function useLocalStorage(key, initialValue) {
      const [localValue, setLocalValue] = useState(() => {
        const storedValue = localStorage.getItem(key);
        return storedValue !== null ? JSON.parse(storedValue) : initialValue;
      });
    
      useEffect(() => {
        localStorage.setItem(key, JSON.stringify(localValue));
      }, [key, localValue]);
    
      return [localValue, setLocalValue];
    }
    

    In this updated version, if storedValue is not null, it will be parsed using JSON.parse(). Otherwise, the initialValue passed to the hook will be used as the default value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search