简体   繁体   中英

What is the point to use useCallback in a component without React.memo?

Consider example:

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>
  );
};

With every state change in App (click the button), the Child component re-renders, even if the passed prop fn is wrapped with useCallback . However, if I wrap Child with React.memo , it starts to work correctly - it does not re-render when parent re-renders.

My question: What's the point of using useCallbacks without React.memo ?? Should I always use React.memo if I dont want the component to always re-render if its parent re-renders?

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

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

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>
  );
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM