Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda