如何在 React Hooks 中使用静态变量

How to use static variables with react hooks

使用 const [open, setOpen] = useState(false) 我可以创建一个变量 open,该变量在功能组件的调用中保持不变。

但是如果我不想在设置变量时重新渲染,我可以使用哪个钩子?

我有一个自定义挂钩草稿:

const useVariable = (initialValue) => {
  const ref = useRef();


  return useMemo(() => {
    ref.current = [initialValue, (newValue) => { ref.current[0] = newValue }]
  }, [])
}

但根据 https://reactjs.org/docs/hooks-reference.html#usememo 我不能相信 useMemo 不会再次调用。

如果你只想将一些数据存储在变量中而不是在设置变量时重新渲染,你可以使用 useRef 钩子

const unsubCallback = useRef(null);

if(!unsubCallback) {
    unsubCallback.current = subscribe(userId)
}

感谢@shubham-khatri,我找到了问题的解决方案。只需使用 useRef 钩子的初始值:

const useVariable = initialValue => {
  const ref = useRef([
    initialValue,
    param => {
      ref.current[0] = typeof param === "function"
        ? param(ref.current[0])
        : param
}
  ]);
  return ref.current;
};

https://codesandbox.io/s/v3zlk1m90

编辑:为了解释 Christopher Camp 的评论,我补充说也可以像在 useState 中一样传递一个函数。请参阅 codesandbox

中的用法