setInterval with setState in React

前端 未结 2 1299
闹比i
闹比i 2021-02-07 12:25

I have a timer using setInterval() in a React component and I\'m unsure what the best practices are in order to start and stop this interval in respect to using

2条回答
  •  天涯浪人
    2021-02-07 12:55

    Using React Hooks useState and useEffect you can do the following:

    const [timer, setTimer] = useState(1);
    
    useEffect(() => {
      const timerId = setInterval(() => setTimer(timer + 1), 1000);
    
      return () => clearInterval(timerId);
    });
    

提交回复
热议问题