什么时候使用没有 deps 的 useEffect?

When to use useEffect with no deps?

如果我没有 deps,为什么以及什么时候应该使用 Effect?

有什么区别(来自React docs):

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

没有useEffect?

function usePrevious(value) {
  const ref = useRef();

  ref.current = value;

  return ref.current;
}

这两种方法的区别在于 useEffect 在渲染周期完成后是 运行,因此 ref.current 将保持之前的值,而在第二种方法中,您的 ref.current 将立即更新,因此前一个值将始终等于当前值

示例演示

const {useRef, useEffect, useState} = React;
function usePreviousWithEffect(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

function usePrevious(value) {
  const ref = useRef();

  ref.current = value;

  return ref.current;
}
const App = () => {
   const [count, setCount] = useState(0);
   const previousWithEffect = usePreviousWithEffect(count);
   const previous = usePrevious(count);
   
   return (
      <div>
        <div>Count: {count}</div>
        <div>Prev Count with Effect: {previousWithEffect}</div>
        <div>Prev Count without Effect: {previous}</div>
        <button type="button" onClick={() => setCount(count => count + 1)}>Increment</button>
      </div>
   )
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="app"/>

同时回答你的问题,当你想在每个渲染上执行一些操作时,你传递 useEffect 没有依赖性。但是,您不能设置状态或执行会导致重新渲染的操作,否则您的应用程序将进入循环