Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda