AlterionA
Reactiflux4y ago
28 replies
Alterion

Hindsight – 13-13 May 16

How do you get around the fact that a setInterval completely screws up references to state when used in a useEffect? In this code,
console.log(frame)
always shows 0, but the state does update correctly in the render, and the setFrame works only when it's using a functional update...
import { useState, useEffect } from "react";

export default function App() {
  const [frame, setFrame] = useState(0);

  useEffect(() => {
    const interval = setInterval(
      () => {
        console.log(frame);
        setFrame((oldValue) => oldValue + 1);
      },
      50,
      frame
    );
    return () => clearInterval(interval);
  }, []);

  return (
    <>
      <p>{frame}</p>
    </>
  );
}
Was this page helpful?