自定义 React Hooks 是否应该导致依赖组件的重新渲染?

Should Custom React Hooks Cause Re-Renders of Dependent Components?

我刚刚创建了一个在内部使用 useStateuseEffect 的自定义挂钩。

当我将该挂钩导入另一个 React 函数组件时,调用它 ComponentAComponentA 每当自定义挂钩中的状态发生变化时重新呈现。

当钩子使用 returns 新值时,ComponentA 应该重新渲染是否正确?

请参阅代码中的注释,以获取更多问题说明。

代码:

const ComponentA = props => {
  const myValue = useMyValue();

  // COMMENTS:
  // Whenever myValue returns a new value, ComponentA re-renders
  // This in turn will cause the useMyValue() function to run.
  // Seems unnatural with such a circular effect.
  // Is my suspicion unfounded? Is this how it should work?
}

自定义可以被简单地视为从功能组件内部执行的函数,并且有效地将自定义挂钩中存在的挂钩转移到组件上。因此,如果自定义挂钩中的代码直接在功能组件中编写,通常会导致组件 re-render 的任何更改都会导致 re-render,即使挂钩是自定义挂钩。

钩子是可以使用其他钩子的简单函数,函数不能 return 一个值,除非它被调用, 在这里,如果我们在自定义挂钩中维护 useState 或 useEffect,那么在渲染组件时首先调用自定义挂钩(这里将调用 useMyValue),使用 componentA 的实例,后者又调用其中的 useState 或 useEffect 挂钩,使用相同的 componentA实例,return componentA 的初始化值。

const useMyValue = () => {
  const [count, setCount] = useState(0);
  // ...do something
  return [count, setCount];
};

const ComponentA = (props) => {
  const [value, setValue] = useMyValue();
};

现在,如果正在更新 componentA 中的 value 并且我们正在调用 setValue,它具有来自自定义挂钩的 setCount 的引用,然后计数得到更新,但 useState 也会更新/重新呈现它持有实例的组件,这里是 componentA,并且在重新渲染 componentA 时将再次调用 useMyValue 钩子,后者又再次调用 useState 并接收更新的计数值,最后 return 其更新值到 componentA。