如何使用带有反应钩子的静态变量

vel*_*lop 6 reactjs react-hooks

使用const [open, setOpen] = useState(false)我可以创建一个变量open,该变量通过功能组件的调用而持久化。

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

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

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


  return useMemo(() => {
    ref.current = [initialValue, (newValue) => { ref.current[0] = newValue }]
  }, [])
}
Run Code Online (Sandbox Code Playgroud)

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

vel*_*lop 1

感谢@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;
};
Run Code Online (Sandbox Code Playgroud)

https://codesandbox.io/s/v3zlk1m90

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