Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why this, highlighted, code won't work in React instead of useEffect?

I was told not to use if statement in place of React.useEffect() cause it would result in an endless loop. Now, that it’s no longer an endless loop why this does not work?

var counter = 0;

export default function App() {

  const [isLoggedIn, setIsLoggedIn]= React.useState(false);

  if((localStorage.getItem('loginStatus')==='Logged In') && counter===0) {
    setIsLoggedIn(true);
    counter++;
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

because you’re using the setIsLoggedIn method while the hooks aren’t fully initialized yet.
Instead you have to replace your hook initialization to the following:

const [isLoggedIn, setIsLoggedIn] = React.useState((localStorage.getItem('loginStatus')==='Logged In') && counter===0);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading