Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

265
Vistas
React, losing saved data in localStorage with useEffect after page refresh

This is probably a noob question, but I'm facing some troubles with the useEffect() hook. I have a Taking Notes App, and I want to make the data persist. I'm using 2 useEffects: one for when the page is refreshed/loaded by the first time, and other one for when I add a new note to my app.

I putted some logs to check what's happening:

const [notes, setNotes] = useState([
  {
  noteId: nanoid(),
  text: 'This is my 1st note!',
  date: '30/07/2022'
  },
  {
    noteId: nanoid(),
    text: 'This is my 2nd note!',
    date: '30/07/2022'
  }
])

// 1st time the app runs
useEffect(() => {
  const savedNotes = JSON.parse(localStorage.getItem('react-notes'))
  console.log('refresh page call:',savedNotes)

  if(savedNotes) {
    setNotes(savedNotes)
  }
}, [])

//every time a new note is added
useEffect(() => {
  localStorage.setItem('react-notes', JSON.stringify(notes));
  console.log('new note call:', notes)
}, [notes])

The behaviour is a bit strange, because when the page is refreshed the new data is appearing inside the log, but then it disappears, maintaining only the hardcoded data:

enter image description here

It also makes more calls than I was expecting to. Any thoughts about what is going on here?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Issue

The problem is caused by the below useEffect and how you are initially setting the state:

useEffect(() => {
  localStorage.setItem('react-notes', JSON.stringify(notes));
  console.log('new note call:', notes)
}, [notes])

The above useEffect runs every time notes changes, but also on mount. And on mount the state is equal to that initial array given to useState. So the localStorage is set to that array.

Solution

A solution is to change how you are setting the state as below, so you pick what's in the localStroge if there is something, and otherwise use that initial array you have:

const [notes, setNotes] = useState(
  !localStorage.getItem("react-notes")
    ? [
        {
          noteId: nanoid(),
          text: "This is my 1st note!",
          date: "30/07/2022",
        },
        {
          noteId: nanoid(),
          text: "This is my 2nd note!",
          date: "30/07/2022",
        },
      ]
    : JSON.parse(localStorage.getItem("react-notes"))
);
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda