T
T
TheSnegok2022-04-17 16:56:07
React
TheSnegok, 2022-04-17 16:56:07

Why doesn't useState change its value in setInterval?

const [stroke, setStroke] = useState(0);

  const updateStroke = () => {
    let timer = setInterval(() => {
      if (stroke > 1250) {
        setStroke(1256);
        clearInterval(timer)
      }
      console.log(stroke);
      setStroke(stroke => stroke + 250);
    }, 1000);
  };

There is a svg circle whose strokeDashoffset should change depending on the state, but when the interval is called, setInterval includes one value and does not change = 0, it works with the usual number and the interval stops, useRef does not work either.
<svg
          className="loadingRing"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          onClick={() => updateStroke()}
        >
          <circle
            r="200"
            cx="210"
            cy="210"
            style={{ strokeDashoffset: stroke }}
          />
        </svg>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2022-04-17
@TheSnegok

When the timer was created, the stroke value was 0, which falls into the closure. Calls to setStroke change the value in the hook, of course, but the variable in the closure doesn't change.
It is necessary to bring all the logic "inside" setStroke.

const updateStroke = () => {
    let timer = setInterval(() => {
        setStroke(stroke => {
            console.log(stroke);
            if (stroke > 1250) {
                clearInterval(timer);
                return 1256;
            } else {
                return stroke + 250;
            }
        });
    }, 1000);
};

Haven't tested it, but offhand it should work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question