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

198
Views
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 answers
Answer question

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 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!