- Procedure:
const nextValue = counter + limit_counter; -> In here, nextValue = 2
console.log("haha", nextValue);
setCounter(nextValue); -> nextValue =2 for counter
console.log({ counter }); //but when I check, why is counter = 1 ??????
-
Example images:
enter image description here -
There is App root:
enter image description here -
There is MainCounter component:
enter image description here
Could you explain me the reason why?? Thank you ^^
const nextValue = counter + limit_counter; -> In here, nextValue = 2
console.log("haha", nextValue);
setCounter(nextValue); -> nextValue =2 for counter
console.log({ counter }); //but when I check, why is counter = 1 ??????
I think in line 4, counter should equal to ‘2’ or I missed something?
2
Answers
React’s setState function is async, which means you have to do something like this :
Use the callback version of the
setCounter
function.You will need an effect that listens for changes to
counter
.Note: In your provided code (screenshot), your
CounterMain
component is a controlled component. It manages its own state, so you do not need a counter inApp
. Also,increaseValue
is unused.Note: Your
App
andCounterMain
components both have a counter state. If you need to hoist the state, move it toApp
.If you want to share the state, you can use a context: