0

Basically, I'm trying to change a React's state by calling a setter method in another function. The first 2 methods changes my state, but the third one doesn't do so right away (I bound all the calls to an onClick event and then just went ham on the button)

const [var1, setVar1] = useState(null)
const foo = () => {
     console.log(var1)
     setVar1("hello world")
     console.log(var1)
}
...<button onClick={foo}>test</button> //logs("hello world" ; "hello world")
...<button onClick={() => {foo()}}>test</button> //logs("hello world" ; "hello world")
...<button onClick={() => {foo("test")}}>test</button> //logs(null ; null) //pressing again log("hello world"; "hello world")

Funnily enough, if I changed foo to accept AND uses a variable, the third call would log ("hello world", "hello world"), but if I don't use the variable it'll return null on the first try, then on second click it'll show the state being changed

const foo2 = (testVar) => {
     console.log(var1)
     setVar1(testVar)
     console.log(var1)
} 
...<button onClick={() => {foo2("hello world")}}>test</button> //logs("hello world"; "hello world")

const foo3 = (testVar) => {
     console.log(var1)
     setVar1("the inner hello world")
}
...<button onClick={() => {foo2("hello world")}}>test</button> //logs(null; null) // second click onward logs ("the inner hello world"; "the inner hello world")

Also, while we're on this topic, does anyone know why it logs "hello world" even before the setter setVar1() get called?

Kevin Bui
  • 1
  • 1
  • 2
    Welcome to SO! See [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – ggorlen Jul 05 '21 at 22:54
  • It's difficult to know if your question is about the different ways to attach a callback (it seems so at the surface), but also that you don't understand the log output because you seem to also not understand the React component lifecycle, how React state updates are asynchronously processed, and how Javascript enclosures work (which is the more apparent issue). – Drew Reese Jul 05 '21 at 23:08

0 Answers0