Why is the cleanup function from `useEffect` called on every render?

前端 未结 5 1223
礼貌的吻别
礼貌的吻别 2020-12-18 18:29

I\'ve been learning React and I read that the function returned from useEffect is meant to do cleanup and React performs the cleanup when the component unmounts

5条回答
  •  执笔经年
    2020-12-18 19:03

    As others have said, the useEffect was depending on the changes of "array" that was specified in the 2nd parameter in the useEffect. So by setting it to empty array, that'd help to trigger useEffect once when the component mounted.

    The trick here is to change the previous state of the Array.

    setArray((arr) => arr.concat("hello"));
    

    See below:

      useEffect(() => {
         const id = setInterval(() => {
             setArray((arr) => arr.concat("hello"));
         }, 3000);
         myRef.current = id;
         return () => {
            console.log("unmount");
            clearInterval(myRef.current);
         };
      }, []);
    

    I forked your CodeSandbox for demonstration: https://codesandbox.io/s/heuristic-maxwell-gcuf7?file=/src/index.js

提交回复
热议问题