React hook missing dependency of custom hook setter

use*_*075 7 typescript reactjs eslint

I'm well aware of what the Hook has missing dependency is, what it means and why it's important to watch all dependencies, but this one is just weird.

export function Compo() {
  const [value, setValue] = useState<number>();

  useEffect(() => {
    setValue(Date.now());
  }, []);

  return (
    <>{value}</>
  );
}
Run Code Online (Sandbox Code Playgroud)

works fine, but:

function useValue() {
  return useState<number>();
}

export function Compo() {
  const [value, setValue] = useValue();

  useEffect(() => {
    setValue(Date.now());
  }, []);

  return (
    <>{value}</>
  );
}
Run Code Online (Sandbox Code Playgroud)

show the well known React Hook useEffect has a missing dependency: 'setValue'. Either include it or remove the dependency array react-hooks/exhaustive-deps.

dcw*_*her 8

您在示例中注意到的是规则的一个怪癖react-hooks/exhaustive-deps。它赋予它所知道的钩子特殊的特权,并且知道在某些情况下是“稳定的”。

引用实现:

// Next we'll define a few helpers that helps us
// tell if some values don't have to be declared as deps.

// Some are known to be stable based on Hook calls.
// const [state, setState] = useState() / React.useState()
//               ^^^ true for this reference
// const [state, dispatch] = useReducer() / React.useReducer()
//               ^^^ true for this reference
// const ref = useRef()
//       ^^^ true for this reference
// False for everything else.
Run Code Online (Sandbox Code Playgroud)

来源: https: //github.com/facebook/react/blob/v17.0.1/packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js#L152

具体来说,这部分规则似乎是useState在这些情况下免除钩子设置器的内容:

// Next we'll define a few helpers that helps us
// tell if some values don't have to be declared as deps.

// Some are known to be stable based on Hook calls.
// const [state, setState] = useState() / React.useState()
//               ^^^ true for this reference
// const [state, dispatch] = useReducer() / React.useReducer()
//               ^^^ true for this reference
// const ref = useRef()
//       ^^^ true for this reference
// False for everything else.
Run Code Online (Sandbox Code Playgroud)

钩子的有用/聪明的不幸结果是,它可能会导致推理不起作用的混乱,就像您刚刚描述的场景一样。

  • 我想我从未见过有人如此深入地做出回应,谢谢您的努力!所以基本上我只需要找到一种解决方法。我认为该规则不够强大,无法通过自定义挂钩找到动态引用。知道我该如何解决它吗? (2认同)
  • 将 setter 包含在依赖项数组中并没有什么坏处,只是您“不需要”进行足够深入的推断。与 useState 相同,您仍然可以在不改变行为的情况下添加它,只是 eslint 插件足够“智能”,知道您不需要它。 (2认同)