Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
checkbox state is not updating on spot

On save, I want to proceed with a function depending if a checkbox have been ticked or not. If the checkbox have been ticked, the function should proceed with the save, otherwise it should display a warning that the checkbox needs to be checked.

However, my functionality is not working. I noticed that if I console.log the checkbox boolean from the state, the state wasn't updated at the time I am calling the function.


  const [checkBoxTick, setCheckBoxTick] = useState(false);
  const [checkBoxError, setCheckBoxError] = useState(false);


  const onSave = useCallback(async () => {
    console.log(checkBoxTick);
    if (checkBoxTick) {
        *** go ahead and save ****
    } else {
      setCheckBoxError(true);
    }
  }, []);


  <Checkbox
    label="text here"
    helperText="This field is required"
    error={checkBoxError}
    onChange={() => setCheckBoxTick(!checkBoxTick)}
  />


   <Button color="primary" size="small" onClick={onSave}>
       Save
  </Button>

When I check the checkBox (which changes the state of checkBoxTick to true) and hit the button, the function gets called but the state of checkBoxTick is false although it should be true.

I know its a common state problem and the whole internet is recommending using useEffect(), but I couldn't make sense of how to use it in my case.

Any help is much appreciated :)

Thank you in advance.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

UseCallback is memoizing the state of checkBoxTick. You need to pass the variable as a dependency to useCallback so that it gets updated, like so:

  const onSave = useCallback(async () => {
    console.log(checkBoxTick);
    if (checkBoxTick) {
        *** go ahead and save ****
    } else {
      setCheckBoxError(true);
    }
  }, [checkBoxTick]);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!