Ido
Ido

Reputation: 5768

setInterval in React - unexpected behavior

I wrote a simple stopwatch in react.
In order to render new number every second I used setInterval:

import React, {useEffect, useState, useRef} from 'react';

const MAX_TIMER = 5;

export default function StopWatch() {
  const [timer, setTimer] = useState(0);
  const tickIntervalId = useRef(null);

  const tickTimer = (getTimerTimeFn) => {
    const number = getTimerTimeFn();

    setTimer(number);

    if(number === MAX_TIMER) {
      clearInterval(tickIntervalId.current);
    }
  }

  let i = 0;
  console.log('i is: ', i) // i value is 0 every render
  const incrementNumber = () => {
    i += 1;
    console.log('in incrementNumber, i is: ', i); // i value is incrementing every render: 1, 2, 3, 4, 5. how?

    return i;
  }

  useEffect(() => {
    tickIntervalId.current = setInterval(tickTimer, 1000, incrementNumber);
  }, [])

  return (
    <div>
      {timer}
    </div>
  );
}

Code Sandbox

The question is- why is this stopwatch working as expected?
Since every second I re-render the component, the line let i = 0 is executed again, so I expect that the returned value from incrementNumber will always be 1 (0 + 1)
But instead, the returned value is incrementing: 1,2,3,4,5.
This is the console output:

i is:  0
in incrementNumber, i is:  1
i is:  0
in incrementNumber, i is:  2
i is:  0
in incrementNumber, i is:  3
i is:  0
in incrementNumber, i is:  4
i is:  0
in incrementNumber, i is:  5
i is:  0

Upvotes: 0

Views: 248

Answers (4)

terrymorse
terrymorse

Reputation: 7096

Here's a little example to demonstrate the lexical scoping issue.

function myFn() {
  
  let i = 0; // `i` is local to myFn() (has local scope)
  console.log(`myFn i == ${i}`);
  
  return (caller) => {
    i++;
    console.log(`${caller} : i == ${i}`);
  }
}

let a = myFn(); // 'myFn i == 0'
a('a'); // 'a : i == 1'

let b = myFn(); // 'myFn i == 0'
b('b'); // 'b : i == 1'
b('b'); // 'b : i == 2'
b('b'); // 'b : i == 3'

a('a'); // 'a : i == 2'

Upvotes: 2

Daniel B. Chapman
Daniel B. Chapman

Reputation: 4687

@Ido

Here's a link to something that makes more sense: I'm using an object so you can see where the variable was stored. I've also upvoted all the other answers as they're correct. Its a scope issue, not a React issue.

https://codesandbox.io/s/material-demo-wj0pm

import React, { useEffect, useState, useRef } from "react";

const MAX_TIMER = 5;

let renderCount = 0;
export default function StopWatch() {
  const [timer, setTimer] = useState({});
  const tickIntervalId = useRef(null);

  const tickTimer = getTimerTimeFn => {
    const number = getTimerTimeFn();

    setTimer({...number});

    if (number === MAX_TIMER) {
      clearInterval(tickIntervalId.current);
    }
  };

  var iObject = {
    i: 0,
    inRender: renderCount,
  };
  renderCount++;
  console.log("i is: ", JSON.stringify(iObject) ); // i value is 0 every render
  const incrementNumber = () => {
    iObject.i += 1;
    console.log("in incrementNumber, i is: ", JSON.stringify(iObject)); // i value is incrementing every render: 1, 2, 3, 4, 5. how?
    console.log("------------------------");
    return iObject; //Not a copy
  };

  useEffect(() => {
    tickIntervalId.current = setInterval(tickTimer, 1000, incrementNumber);
  }, []);

  return <div>{JSON.stringify(timer)}</div>;
}

enter image description here

Upvotes: 2

M. Koch
M. Koch

Reputation: 27

I believe it is a matter of scope, if you give console.log (i) in useEffect we can see that it only logs in the first rendering. As if the let i inside the useEffect is different than that of the component. Even with the new rendering, the state in useEffect remains.

  useEffect(() => {
    console.log("i in effect: ", i)
    tickIntervalId.current = setInterval(tickTimer, 1000, incrementNumber);
  }, []);

Upvotes: 1

MUHAMMAD ILYAS
MUHAMMAD ILYAS

Reputation: 1450

You need to know about the lexical environment and execution context and how the scope work

Already discussed here almost similar example
https://stackoverflow.com/a/19123476

Upvotes: 2

Related Questions