Arii
Arii

Reputation: 411

Will React memoize component created during children.map?

If I have a setup like the following:

const ChildComponent = React.memo((props) => {
   return (<>...</>);
});

const ParentComponent = (props) => {
   return (
      {React.Children.map(props.children, child => {
         return <div>{child}</div>;
      )}
   );
}

Assuming child.props are identical, will React know to memoize child or will it rerender each time?

Upvotes: 1

Views: 843

Answers (1)

Arii
Arii

Reputation: 411

Changed the setup to the following:

const ChildComponent = React.memo((props) => {
   return (<p>{props.a}</p>);
}, (prev, next) => {
   if (prev.a === next.a) { console.log('memo'); return true; }
   console.log('no memo'); return false;
});

const ParentComponent = (props) => {
   return (
      {React.Children.map(props.children, child => {
         return <div>{child}</div>;
      )}
   );
}

const App = () => {
   return (
      <ParentComponent>
          <ChildComponent a='a'/>
          <ChildComponent a='b'/>
          <ChildComponent a='c'/>
      </ParentComponent>
   );
}

And I see memo in console. This doesn't seem to be like an exhaustive answer by any means, but I'd assume this means it works.

Upvotes: 2

Related Questions