3

I'm trying to understand how hooks works in React. I have some example with counter, but don't understand why logs looks like that. First console.log is 5 - because setState is a asynchronous function. But next results are strange. Why 'state in setInterval' is always 5 and 'state' twice is 6?

I prepared some example:

function Counter() {
  const [state, setState] = React.useState(5);
  React.useEffect(() => {
    setInterval(() => {
      setState(state + 1);
      console.log('state in setInterval', state);
    }, 5000);
  }, []);

  console.log('state', state);
  return (
    <React.Fragment>
      <h2>Counter: {state}</h2>
    </React.Fragment>
  );
}
ReactDOM.render(
  <Counter />,
  document.getElementById('root')
);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

(Also on CodePen)

skyboyer
  • 22,209
  • 7
  • 57
  • 64
whity
  • 65
  • 1
  • 7

0 Answers0