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

76
Visualizações
setState in useEffect not update

Got an input and want to pass value to handler:

const [term, setTerm] = useState('');

<Input type="text" onBlur={(e)=>handleFilter(e, 'params')} />

const handleFilter = async(e, params) => {
//... api call and etc
setTerm(e.target.value); // update term
console.log(term) // return none-updated value! but I need fresh value
// send this value to another api
}

I want to make an search filter function, for ex. if I enter a, console return empty, then I enter b console return a ! it means term not update immediately, then I used useEffect but inside the useEffect I got new value, but inside handleFilter function still console return prev value.

useEffect(() => {
    getApi()
        .then(data => {
            console.log(data)
        })

    console.log(term) // works fine, return new value
    setTerm(term) // update term

}, [term])

I tried this but no success:

setTerm({...term, e.target.value});

Any solution? I'm new to react hook.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can check this answer here.

This is because react's state update is async. You can't rely on its update right after calling setState. Put your effects (code that is run after a state is updated) in a useEffect hook.

const handleFilter = async(e, params) => {
  //... api call and etc
  setTerm(e.target.value); // update term
}

React.useEffect(() => {
  console.log(term) // return none-updated value! but I need fresh value
  // send this value to another api
}, [term]);
about 4 years ago · Juan Pablo Isaza Relatório

0

setTerm is async and will update the term on the next render cycle. it is not updated immediately for the current render cycle. you can store the current value in a ref if you are curious what is happening behind the scenes

const termRef = React.useRef(term);
termRef.current = term;
const yourHandler = () => {
  setTimeout(() => console.log(termRef.current), 0);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

If we are going ahead with useEffect with an API call, please ensure to include async await scenario to ensure that setState updates after the data is fetched.

useEffect(async () => {
    const data = await getApi()
      

    console.log(term) // works fine, return new value
    setTerm(term) // update term

}, [term])

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