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

452
Views
UseState renders me the previous state

I have two inputs that change the text of a P tag at the same time, but the problem is that the render that shows me is always the previous value that was saved. I understand that I have to use a useEffect to render the component again and show the current value, but in the inputs handleChange if or if I need to send to the SetState that changes the text, the value that was saved in the initialValue. Until now I am learning React and I have already tried a lot of things, but nothing works for me, how could I implement the useEffect in this case? Thank you very much for the help.

const initialValue = {
  input1: 0,
  input2: 0,
};

const TestState = () => {
  const [obj, setObj] = useState(initialValue);
  const [textChange, setTextChange] = useState("-");

  useEffect(() => {}, [obj]);

  const handleChange = (e) => {
    setObj({ ...obj, [e.target.name]: e.target.value });
    //Basically I need to do this -> setTextChange(e.target.value), but with the value stored in the initialValue.
    setTextChange(e.target.name === "input1" ? obj.input1 : obj.input2);
  };

  return (
    <div>
      <form>
        <input type="text" name="input1" onChange={handleChange} />
        <input type="text" name="input2" onChange={handleChange} />
      </form>
      <p>{textChange}</p>
    </div>
  );
};

https://codesandbox.io/s/practical-mahavira-pd94p?file=/src/TestState.js

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The setter you get from useState (i.e. setObj) does not immediately alter the value/state of the object under control. The update occurs before the next render(). That is why your obj object appears to be stale.

Note, you don't need to replace the obj object itself, you're just updating its contents. You could just do this:

const [obj] = useState(initialValue);
...

const handleChange = (e) => {
  //setObj({ ...obj, [e.target.name]: e.target.value });
  obj[e.target.name] = e.target.value;
  setTextChange(e.target.name === "input1" ? obj.input1 : obj.input2);
}
about 4 years ago · Juan Pablo Isaza Report
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!