Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

98
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda