[React] useEffect - problem: depending On State Mutated In The useEffect

Let say we have a simple counter app:

import { useEffect, useState } from "react";

function useStopwatch() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("useStopwatch");
    const interval = setInterval(() => {
      console.log(`Count = ${count}`);
      setCount(count + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, [count]);

  return count;
}

export default function App() {
  const count = useStopwatch();
  return (
    <div className="App">
      <h2>{count}</h2>
    </div>
  );
}

Everytime, `count` get mutated, `useStopwatch` will be trigger to re-run:

This is because, `useEffect` is deps on `count`. 

 

The way we can solve the problem by decouple the `count` with `useEffect`

function useStopwatch() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("useStopwatch");
    const interval = setInterval(() => {
      console.log(`Count = ${count}`);
      setCount((prev) => prev + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  return count;
}

setCount((prev) => prev + 1);

Custom hook is triggered much less times and we no longer deps on mutated state `count`

posted @   Zhentiw  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-10-26 [CSS] Use CSS Transforms to Create Configurable 3D Cuboids
2020-10-26 [CSS] Use CSS Variables Almost like Boolean Values with Calc (maintainable css)
2020-10-26 [Kotlin] Typecheck with 'is' keyword, 'as' keyword for assert type
2020-10-26 [Kotlin] When to add () and when not to
2020-10-26 [Kotlin] fold / reduce
2016-10-26 [CSS] Control Image Aspect Ratio Using CSS (object-fit)
2016-10-26 [Angular2 Form] Reactive form: valueChanges, update data model only when form is valid
点击右上角即可分享
微信分享提示