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

99
Vistas
React How to re-render state hook with useEffect and useCallback?

I apologize for asking this question. I've read many posts on how to re-render the state but I still can't figure it out. I'm too noob :( I can get things to work with useRef, but I'd like to learn how to update state with useEffect and useCallback. My database fetch requires a second click to fire because setState is asynchronous. Neither of my useEffect/useCallback updates state :( useEffect is firing, I'm getting the console log.

export function Form() {
    const[inputKey, setInputKey] = useState("");
    const inputKeyRef = useRef();

    const [keyValid, setKeyValid] = useState(false);
    useEffect(() => {
        console.log("keyValid:", keyValid)
    }, [keyValid])

    const [keyAuthentic, setKeyAuthentic] = useState(false);
    useEffect(() => {
        console.log("keyAuthentic:", keyAuthentic)
    }, [keyAuthentic])

    const updateKeyValid = useCallback(
        () => setKeyValid(true),
        [keyValid, setKeyValid]
    )

    const submit = e => {
        e.preventDefault();
        if ( !inputKeyRef.current.value.length < 12 || !inputKeyRef.current.value.length < 20 ) {
            setKeyValid(true) // not updating state
            updateKeyValid(); // not updating state
        }

        if ( keyValid === true ) { // state not true if keyValid(true)
            db.collection("users").doc(inputKey).get().then((doc) => {
                if (doc.exists) {
                    setKeyAuthentic(true)
                    console.log(doc.data())
                }
            });
        }
    };

    return (
        <div className="form__submit">
            <Button type="submit" onClick={submit}}>Submit</Button>
        </div>
    )
}

export default Form
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As you noted, setKeyValid is async, so you won't have access to the new value until the next render.

You effects don't call any setState functions so I'm not sure why you would expect state to be updated inside them.

Also, state shouldn't be deterministic. If you can determine what a value should be on any render based on some other state, then you don't need useState at all. Like:

export function Form() {
  const [keyAuthentic, setKeyAuthentic] = useState(false);
  const [inputKey, setInputKey] = useState("");

  const submit = e => {
      e.preventDefault();
      
      const valid = !inputKey.length < 12 || !inputKey.length < 20;
      if (!valid) return;

      db.collection("users").doc(inputKey).get().then((doc) => {
          if (doc.exists) {
              setKeyAuthentic(true)
              console.log(doc.data())
          }
      });
  };

  return (
      <div className="form__submit">
          <Button type="submit" onClick={submit}}>Submit</Button>
      </div>
  )
}
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