Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!