Home > Mobile >  React non state variables inside function component are not updated instantly
React non state variables inside function component are not updated instantly

Time:10-17

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 = ()=>{
        c = c 1;
        console.log(c);
        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?

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related