Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
ReactJS localstorage.getItem is not working

i have a problem with the localstorage.getItem, the setItem function is working fine and the data is stored correctly but when i refresh the page the data is gone. Here is my codes

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

 useEffect(()=>{
    const storage = JSON.parse(localStorage.getItem(local_Storage_key));
    if (storage) {setContacts(storage);}
    }, []);

picture of the localstorage before i refresh the page

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

I think that's because your below code is executing after component has been mounted.

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

And because of this it is setting the initial value of contacts into the localStorage again. To avoid this you can set the initial value of contacts to the value you get from the localStorage

const [contacts,setContacts] = useState(JSON.parse(localStorage.getItem(local_Storage_key)));

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

// remove another useEffect
about 4 years ago · Santiago Gelvez Report

0

I suggest you use useLocalStorage

import { useLocalStorage } from 'react-use';

const Demo = () => {
  const [value, setValue, remove] = useLocalStorage('my-key', 'foo');

  return (
    <div>
      <div>Value: {value}</div>
      <button onClick={() => setValue('bar')}>bar</button>
      <button onClick={() => setValue('baz')}>baz</button>
      <button onClick={() => remove()}>Remove</button>
    </div>
  );
};
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!