Home > other >  Why setInterval creates a closure in the reactjs counter?
Why setInterval creates a closure in the reactjs counter?

Time:11-12

Below is official example in React document. The official explanation is

The problem is that inside the setInterval callback, the value of count does not change, because we’ve created a closure with the value of count set to 0 as it was when the effect callback ran.

Can you show me where is the closure? I don't understand why the closure making the counter only reaches 2. I know closure, useEffect(), ()=> {} will not create a closure, but I don't understand how those concepts play together in this example to make the counter bug.

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

function Counter() {
  const [count, setCount] = useState(1);

  useEffect(() => {
    const id = setInterval( () => {
      console.log("interval callback triggered");
      setCount(count   1); // This effect depends on the `count` state
    }, 1000);
    return () => clearInterval(id);
  }, []); //            
  • Related