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

In React why does my boolean repeats itself?

import React from "react"

export default function App() {
    const [isImportant, setIsImportant] = React.useState("Yes")

    let isImportantBoolean = false;
    function handleClick() {
        isImportantBoolean = !isImportantBoolean;
        isImportantBoolean ? setIsImportant('Yes') : setIsImportant('No');
        console.log(isImportantBoolean);
    }
    
    return (
        <div className="state">
            <h1 className="state--title">Is state important to know?</h1>
            <div onClick={handleClick} className="state--value">
                <h1>{isImportant}</h1>
            </div>
        </div>
    )
}

When I click the button the console.log pattern goes like true false true true false it repeats the true. But when I remove the isImportantBoolean ? setIsImportant('Yes') : setIsImportant('No') console.log goes normal and does not repeat true. Why is this behaviour is occuring?

>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

Your isImportantBoolean gets reset and re-defined on every render that happens after you set your isImportant state. You should do things vise-versa and store your boolean value there instead, and conditionaly display either "Yes" or "No" based on boolean value

import React from "react"

export default function App() {
  const [isImportant, setIsImportant] = React.useState(true)

  function handleClick() {
      setImportant(!isImportant);
      console.log(isImportant);
  }

  return (
      <div className="state">
          <h1 className="state--title">Is state important to know?</h1>
          <div onClick={handleClick} className="state--value">
              <h1>{isImportant ? "Yes" : "No"}</h1>
          </div>
      </div>
  )
}
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