首页 > 解决方案 > 使用自定义 Hook 防止组件重新渲染

问题描述

我有一个自定义挂钩useWindowSize,可以监听窗口大小的变化。一旦窗口大小低于某个阈值,一些文本应该会在Menu. 这是在另一个自定义钩子useSmallWindowWidth中实现的,该钩子接受返回的值useWindowSize并检查它是否小于阈值。

然而,即使只有嵌套状态发生变化,当窗口大小发生变化时,我的组件也会不断地重新呈现。重新渲染菜单平均需要大约 50 毫秒,如果我想让其他组件也响应的话,这会加起来。

那么我怎样才能防止组件重新渲染呢?我尝试React.memo通过return prev.smallWindow === next.smallWindow;在函数内部传递,但它没有用。

到目前为止我的尝试:

//this hook is taken from: https://stackoverflow.com/questions/19014250/rerender-view-on-browser-resize-with-react

function useWindowSize() {     
    const [size, setSize] = useState([0, 0]);
    useLayoutEffect(() => {
      function updateSize() {
        setSize([window.innerWidth, window.innerHeight]);
      }
      window.addEventListener('resize', updateSize);
      updateSize();
      return () => window.removeEventListener('resize', updateSize);
    }, []);
    return size;
  }

function useSmallWindowWidth() {
  const [width] = useWindowSize();
  const smallWindowBreakpoint = 1024;
  return width < smallWindowBreakpoint;
}

function Menu() {
  const smallWindow = useSmallWindowWidth();
  return (
    <div>
      <MenuItem>
        <InformationIcon/>
        {smallWindow && <span>Information</span>}
      </MenuItem>
      <MenuItem>
        <MenuIcon/>
        {smallWindow && <span>Menu</span>}
      </MenuItem>
    </div>
  );
}

标签: reactjsreact-hooksreact-memo

解决方案


您可以尝试将所有 JSX 包装在 useMemo 中

function App() {
  return useMemo(() => {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }, []);
}

将数组放入 useMemo 的第二个参数中,什么变量应该使您的 jsx 重新呈现。如果设置了一个空数组(如示例中),则 jsx 永远不会重新呈现。


推荐阅读