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

200
Vistas
Why is my conditional statement not working as expected in useEffect hook?

It seems that the if-statement in my useEffect hook is evaluating, even though the condition is false. Why is this happening?

My code:

useEffect(() => {
  console.log(localStorage.getItem("darkMode"))
  if (localStorage.getItem("darkMode")) {
    console.log(localStorage.getItem("darkMode"))
  }
}, [])

The console: Console showing false twice

My code compiles with no warnings or errors, and my useEffect function is in the top-level of my App component.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The issue is that localStorage.getItem always returns a string (or null if there is no value). Because of that it will always run the code inside the if-block unless the string is empty.
You can either parse the string with JSON.parse or simply check for equality to "true".

useEffect(() => {
  console.log(localStorage.getItem("darkMode"))
  if (localStorage.getItem("darkMode") === "true") {
    console.log(localStorage.getItem("darkMode"))
  }
}, [])

or

useEffect(() => {
  const mode = JSON.parse(localStorage.getItem("darkMode"));
  console.log(mode);
  if (mode) {
    console.log(mode)
  }
}, [])
about 4 years ago · Juan Pablo Isaza 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