Home > Mobile >  In React why does my boolean repeats itself?
In React why does my boolean repeats itself?

Time:10-14

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?

CodePudding user response:

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>
  )
}
  • Related