0

How to memoize nested function? For e.g., if we have following memoized components App, Test, OtherComponent

const App = React.memo(() => {
  const handleChange = useCallback((rowData) => (option) => {},[]);
  return <Test data={data} handleChange={handleChange} />;
});

const Test = React.memo(({ data, handleChange }) =>{
  return (
    <div>
      {data.map((rowData) => (
        <OtherComp handleChange={handleChange(rowData)} />
      ))}
    </div>
  );
});

const OtherComp = React.memo(({ handleChange }) =>{});

React.memo will work only if we pass it memoized functions/objects. If we use useCallback, it won’t memoize inner function and React.memo won’t work for OtherComponent.

user3211534
  • 123
  • 1
  • 2
  • 6
  • You are missing the dependency array as the second argument to `useCallback`. Refer to the [documentation](https://beta.reactjs.org/apis/react/useCallback#usecallback) for more information. It also seems like the `` component is missing the `data` prop which will throw a `TypeError` here. – Erik André Dec 20 '22 at 13:26
  • The code is just for example. However, updated. – user3211534 Dec 20 '22 at 13:28

0 Answers0