setInterval Unlimited re-rendering of react-complete components. Why does this happen and how to fix it?
P粉978742405
P粉978742405 2024-04-03 15:39:05
0
1
505

This is my react code. It makes the component re-render infinitely:

const [seconds, setSeconds] = useState(60)
useEffect(() => {
    const interval = setInterval(() => {
        setSeconds(seconds => seconds - 1);
    }, 1000);
    return () => clearInterval(interval);
}, []);

console.log("object");

P粉978742405
P粉978742405

reply all(1)
P粉476046165

This happens because you only clear the interval when the component unloads, which only happens when the user navigates away from the page.

Maybe this is what you need? When the interval reaches 0, I clear it. But for this I have to use reference, I can't use state from setInterval because it only has initial value:

export default function App() {
  const [seconds, setSeconds] = useState(5);
  const secondsRef = useRef(seconds);

  useEffect(() => {
    const interval = setInterval(() => {
      if (secondsRef.current  seconds - 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  console.log("running", new Date());

  return 

{seconds ; }

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template