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

190
Visualizações
state value inside setTimeout is not same to the updated value in React

I have the following code:

import { useEffect, useState, useRef } from "react";
import ReactDOM from "react-dom";

const Stock = ({ data }) => {
  const chartRef = useRef(null);
  const [myChart, setMyChart] = useState(null);
  const [input, setInput] = useState(0);

  useEffect(() => {
    if (!chartRef) return;
    const myChart = 1;
    setMyChart(myChart);
  }, [data, chartRef]);

  useEffect(() => {
    if (!myChart) return;
    var temp = [];
    for (let index = 0; index < data.length; index++) {
      setTimeout(() => {
        temp.push(data[index]);
        console.log(input);
      }, 3000 * index);
    }
  }, [data, myChart]);

  const changeHandler = (event) => {
    setInput(event.target.value);
  };
  return (
    <div>
      <input onChange={changeHandler} />

      <h1>{input}</h1>
    </div>
  );
};

const App = () => {
  const [res, setRes] = useState({});

  useEffect(() => {
    if (Object.keys(res).length !== 0) return;
    setRes({
      success: true,
      data: [1, 2, 3, 4],
      message: "Successful get data!"
    });
  }, [res]);

  return <div>{res.success ? <Stock data={res.data} /> : null}</div>;
};

ReactDOM.render(<App />, document.getElementById("container"));

When I change the the 'input' state via input field, the state is updated. However, every setTimeout is run, the console log is showing that the value is equal to initial value (which is zero).

How to fix this?

Thanks.

about 4 years ago · Juan Pablo Isaza
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