📌  相关文章
📜  useEffect - 任何代码示例

📅  最后修改于: 2022-03-11 14:56:40.229000             🧑  作者: Mango

代码示例6
//1.

function App() {
  const [isOn, setIsOn] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => console.log('tick'), 1000);

    return () => clearInterval(interval);
  });
}

//2.

function App() {
  const [isOn, setIsOn] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => console.log('tick'), 1000);

    return () => clearInterval(interval);
  }, []);
}

//3. 

function App() {
  const [isOn, setIsOn] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => console.log('tick'), 1000);

    return () => clearInterval(interval);
  }, [isOn]);
}
The first will run the effect on mount and whenever the state changes. The clean up will be called on state change and on unmount.

The second will only run the effect once on mount and the clean up will only get called on unmount.

The last will run the effect on mount and whenever the isOn state changes. The clean up will be called when isOn changes and on unmount.

In your examples, the first and last examples will behave the same because the only state that will change is isOn. If the first example had more state, that effect would also refire if the other state were to change.

I guess I should also add is that the order of things would be like: mount: -> run effect, state change: run clean up -> run effect, unmount -> run clean up.