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

128
Views
Update variable and use it immediately React

I am trying to update a variable after an api call but I will use a click event for this question.

As you can see, the variable that i print uses the old state on the first click as it doesn't register the change yet. On the following calls the variable gets printed with the new text.

Is there a way to use the updated variable immediately within the changeText function?

https://stackblitz.com/edit/react-36jqi3

export default function App() {
  const [text, setText] = useState('inital text');

  const changeText = () => {
    setText('new text');
    console.log(text);
  };

  return (
    <div>
      <button onClick={changeText}>Update variable</button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

No.

The changeText function that is currently running will have closed over the value of text from the value assigned during the render that created the changeText function.

The next render of the component will generate a new changeText function and assign it to onClick.

If you want to use the value you've just passed to setState then keep a copy of that value somewhere else.

const changeText = () => {
  const newValue = 'new text';
  setText(newValue);
  console.log(newValue);
};

Alternatively, do the work that needs the new value in an effect hook that triggers when that value changes.

useEffect(() => {
    console.log(text);
}, [text]);

const changeText = () => {
  setText('new text');
};

That will trigger the hook on the initial render too though so you might want to add an extra test to make sure it isn't the initial value before logging it.

about 4 years ago · Juan Pablo Isaza Report

0

Can get by way.

export default function App() {
  

  const [text, setText] = useState('inital text');


  const changeText = () => {
    /* Calling updater to get the latest value. */
    setText('new text');
    setText((state) => {
       console.log("immediately updated text -->", state); 
       return state;
    });
  };



  return (
    <div>
      <button onClick={changeText}>Update variable</button>
    </div>
  );
}
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!