How to clean up setInterval in useEffect using react hooks

前端 未结 1 1891
迷失自我
迷失自我 2021-02-14 16:26

I am trying to create a loading component that will add a period to a div periodically, every 1000ms using setInterval in React. I am trying to cleanup setInterval using the met

1条回答
  •  旧巷少年郎
    2021-02-14 17:02

    Dependencies are our hint for React of when the effect should run, even though we set an interval and providing no dependencies [], React wont know we want to run it more then once because nothing really changes in our empty dependencies [].

    To get the desired result we need to think when we want to run the effect ?

    We want to run it when loadingStatus changes, so we need to add loadingStatus as our dependency because we want to run the effect every time loadingStatus changes.

    We have 2 options

    Add loadingStatus as our dependency.

    const Loading = () => {
      const [loadingStatus, setLoadingStatus] = useState(".");
      const [loop, setLoop] = useState();
    
      useEffect(
        () => {
          setLoop(
            setInterval(() => {
              console.log("loading");
              setLoadingStatus(loadingStatus + ".");
            }, 1000)
          );
    
          return function cleanup() {
            console.log("cleaning up");
            clearInterval(loop);
          };
        },
        [loadingStatus]
      );
    
      return 

    {`Loading ${loadingStatus}`}

    ; };

    Make our effect not aware that we use loadingStatus

    const Loading = () => {
      const [loadingStatus, setLoadingStatus] = useState(".");
    
      useEffect(() => {
        const intervalId = setInterval(() => {
          setLoadingStatus(ls => ls + ".");
        }, 1000);
    
        return () => clearInterval(intervalId);
      }, []);
    
      return 

    {`Loading ${loadingStatus}`}

    ; };

    Read more here => a-complete-guide-to-useeffect

    0 讨论(0)
提交回复
热议问题