在没有 React.memo 的组件中使用 useCallback 有什么意义?

und*_*ood 6 javascript reactjs react-hooks

考虑示例:

const Child = () => {
  console.log("I did re-render!");
  return null;
};

const App = () => {
  const [_, setValue] = useState();
  const fn = useCallback(() => {
    // do something
  }, []);

  return (
    <div>
      <button onClick={() => setValue(Math.random)}>click</button>
      <Child fn={fn} />
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

每次状态更改App(单击按钮)时,Child组件都会重新渲染,即使传递的 propfn是用useCallback. 但是,如果我用 换行ChildReact.memo它就会开始正常工作 - 当父级重新渲染时它不会重新渲染。

useCallbacks我的问题:不使用有什么意义React.memoReact.memo如果我不希望组件在其父级重新渲染时始终重新渲染,我是否应该始终使用?

应该始终与?useCallbacks一起使用 React.memo因为如果没有的话,它们似乎毫无意义、毫无用处React.memo

游乐场:https://codesandbox.io/s/peaceful-khorana-nrojpb? file=/src/App.js

Ben*_*aum 2

My question: What's the point of using useCallbacks without React.memo??

There is none unless you otherwise tell React to compare based on refernece down the line.

Should I always use React.memo if I dont want the component to always re-render if its parent re-renders?

Yes, or something equivalent.

Should useCallbacks always be used with React.memo? Because it seems like they are senseless and useless without React.memo.

Yes, unless you do something equivalent.


Just to elaborate - other than React.memo you can always wrap a sub-render with useMemo:


const App = () => {
  const [_, setValue] = useState();
  const fn = useCallback(() => {
    // do something
  }, []);

  const child = useMemo(() => <Child fn={fn} />, [fn]);
  return (
    <div>
      <button onClick={() => setValue(Math.random)}>click</button>
      {child}
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

Or "roll your own" with useRef+useEffect or use class components and override shouldComponentUpdate or inherit from React.PureComponent.