4

I have an input type checkbox as follow:

const [is_checked,set_is_checked]= useState(false);

const toggle_payment = () => {
    set_is_checked(!is_checked);
    console.log(is_checked);
}


return(
    <div>
        <input checked={is_checked}  onChange={toggle_value} type="checkbox"/>
    </div>
)

The problem

This seems to work fine, But when I console.log(is_checked) it looks like it prints the previous value. I tried both onChange and onClick but got the same result. What confuses me is that the checkbox is getting checked / unchecked each time I click on the box, but the console.log prints different value than what expected to print, like when I check the box with the mouse click, the box got checked but the console.log prints false

2 Answers 2

4

the state update using the updater provided by useState hook is asynchronous, and will not immediately reflect and update but will trigger a re-render

i think that if you console.log() outside the function you might gonna see the changes of the is_checked

Sign up to request clarification or add additional context in comments.

2 Comments

you can check this stackblitz i created: stackblitz.com/edit/react-7jckhn you'll see that if you console.log() the value outside the value is correct "outside Toggle Payment"
you could also do something like this stackblitz.com/edit/react-jchkmr and put the logic inside the useEffect()
1

This is due to the way state management works in React. A call to a state setter function (in this case set_is_checked) will update the value, but that updated value is available on the next render. When you call console.log below set_is_checked, you are still referencing the old value prior to the state being set.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.