useState counter flickers after clicking the button

Viewed 813
export const App2 =()=>{
     const [counter,setCounter]=useState(0)
     setTimeout(()=>setCounter(counter+1),1000)

  
     return(
         <div> {counter}
             <button onClick={()=>{setCounter(counter+1)}}> Plus</button>
         </div>

     )



 }

I recorded a video and uploaded it to youtube. I have no idea why this instability happens and switching tabs made it normal again. Anyone to enlighten? I just made a slight modification to this code

1 Answers

setTimeout causes an effect, so we should put it inside a useEffect() hook. Also, since setCounter depends on the previous counter state, we can pass an updater function to setCounter which receives the previous state value.

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

export const App2 = () => {
  const [counter, setCounter] = useState(0);

  const increment = useCallback(() => {
    setCounter((counter) => counter + 1);
  }, []);

  useEffect(() => {
    const id = setTimeout(increment, 1000);
    return () => clearTimeout(id);
  }, [increment]);

  return (
    <div>
      {" "}
      {counter}
      <button onClick={increment}> Plus</button>
    </div>
  );
};

Related