Answer the question
In order to leave comments, you need to log in
Why, when changing the state of a react component in setInterval, the state value is reset to the original one every time?
Code like this
import React, { useState, useEffect } from 'react';
export const App = (): JSX.Element => {
const [count, setCount] = useState(0);
useEffect(() => {
setInterval(() => {
console.log(count);
setCount(count + 1);
}, 100);
}, []);
return (
<div>
{ count }
</div>
)
}
Answer the question
In order to leave comments, you need to log in
Explanation from the React documentation:
https://ru.reactjs.org/docs/hooks-faq.html#what-ca...
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1); // Этот эффект зависит от переменной состояния `count`
}, 1000);
return () => clearInterval(id);
}, []); // Баг: `count` не указан в качестве зависимости
return <h1>{count}</h1>;
}
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1); // ✅ Эта строчка не зависит от внешней переменной `count`
}, 1000);
return () => clearInterval(id);
}, []); // ✅ Наш эффект не использует никаких переменных из области видимости компонента
return <h1>{count}</h1>;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question