Home > Software engineering >  React state for booleans and numbers not updating, is prev value needed?
React state for booleans and numbers not updating, is prev value needed?

Time:01-06

I might be having one of those days but I am updating state in boolean and numbers, but when I click on the values the old value appears first, and no the value of the button does not depend on the old value, do you still have to use prev value even for boolean, if so how and why?

https://stackblitz.com/edit/react-xj8gka?file=src/App.js

Minimal example in the stackblitz too:

import React, {useState} from "react";
import "./style.css";


export default function App() {

  const [value, setValue] = useState(1)
  const [boolean, setBoolean] = useState(false)

  return (
    <div>

<button onClick={() => {setValue(() => 1)
        console.log(value)
        }}>Value 1</button>

<button onClick={() => {setValue(() => 2)
        console.log(value)
        }}>Value 2</button>
<p>Booleans</p>

<button onClick={() => {setBoolean(() => true)
        console.log(boolean)
        }}>True</button>

<button onClick={() => {setBoolean(() => false)
        console.log(boolean)
        }}>False</button>
      
    </div>
  );
}

CodePudding user response:

you only need to pass a callback function to the setter function setBoolean incase you want to use the old value like this example setBoolean((prevBool) => !prevBool) // toggling the old bool value

while if you want to set a definite value that doesn't depend on the old one you just need to put it directly like this setBoolean(true) i don't see why you would need a callback function to return true

also as Konrad menitioned console.log(value) or console.log(bool) will get you the prev value first then on the next cycle render it will get you the updated value better to put console.log on the body of the component before the return of the jsx

CodePudding user response:

Yes it is recommended to use a function with the the previous value as its first argument. This way, if you change the state twice inside the same component as you did above, the state updating function will have the most recent version of the state.

If you don't use the previous value, your state will only be updated if the component is re-rendered.

  • Related