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

104
Views
React non state variables inside function component are not updated instantly

I know that useState hook of react is asynchronous so if I use useState to store variable and call set function on it, it may not be updated instantly.

However now I am using simple variables to store the value, but still the variable value is not updated. How can I resolve the same?

const List=(props)=>{
    let count = 1;
    const onNextButtonClick = ()=>{
        count  = count +1;
        console.log(count );
        updatePage();
    }
    return (
        //html
    )
}

I see that the value of c is not getting incremented whenever the next button is clicked and I am getting the same value of c on console.

Why is this happening?

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

0

count needs to be stored in state and, because state updates may be grouped and processed asynchronously, you won't see the change until the next render which is where useEffect comes in useful.

const { useEffect, useState } = React;

function Example() {

  const [ count, setCount ] = useState(0);

  function onNextButtonClick() {
    setCount(count + 1);
    // the other thing
  }

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={onNextButtonClick}>
        Click me
      </button>
    </div>
  );
};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></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!