0

I have a question on using useCallback on built-in/ non-custom components in React. Below I provided a simple example.

I wrapped "increment1" in useCallback so it would not be recreated and passed as a new function into MyOwnButton component. Thus, with React.memo, MyOwnButton component would only get rerendered when 'count1' is updated.

Here come my question. Should I wrap "increment2" in useCallback too? So it would not be passed as a new function into the tag (or simplified as "button2") and to prevent "button2" from unnecessary rerendering too?

import React, { memo, useCallback, useState } from 'react';

export default function App() {
  const [count1, setCount1] = useState(0);
  const [count2, setCount2] = useState(0);
  const increment1 = useCallback(() => {
    setCount1((prev) => prev + 1);
  }, []);
  const increment2 = () => setCount2((prev) => prev + 2);

  return (
    <>
      <MyOwnButton count={count1} onClick={increment1} />
      <button onClick={increment2}>button2:{count2}</button>
    </>
  );
}

const MyOwnButton = memo(({ count, onClick }: any) => {
  console.log('MyOwnButton');
  return <button onClick={onClick}>button1:{count}</button>;
});
LY Hooi
  • 165
  • 1
  • 9
  • It might reduce processing a bit (I don't know), but even if so, the improvement would be unnoticeable 99.9% of the time. Regardless of the effect, I wouldn't bother - clear, concise code is more important. – CertainPerformance Jan 29 '22 at 16:45
  • I think if there is function that has more calculation then useCallback us more useful, in react document also they mention used it when there is function with more calculation, if it's simple button i don't think it's give more performance issue – cool_code Jan 29 '22 at 16:53
  • Does this answer your question? https://stackoverflow.com/questions/55310682/should-i-wrap-every-prop-with-usecallback-or-usememo-when-to-use-this-hooks – Lin Du Jun 14 '23 at 06:14

0 Answers0