Pierre Courpron
Pierre Courpron

Reputation: 154

Arrow function vs Component React

I recently made a pull request at my company and got feedback on some code that I had written and I wanted some other opinions on this. We have an component called Icon that can take another component as a prop like so:

<Icon component={ArrowDown}/>

this simply renders the following:

<IconContainer>
    <ArrowDown/>
</IconContainer>

Now you can also do the follow if you need to create a custom icon:

<Icon component={()=><div>custom Icon</div>}/>

The reviewer commented that the function ()=><div>custom Icon</div> should be removed outside the scope for performance reasons to prevent re-rendering:

const CustomIcon = ()=><div>custom Icon</div>
const someComponent = ()=><Icon component={customIcon}/>

I'm not convinced that this will improve performance (code-readability sure) but wanted to get some other opinions on it. Thanks!

Upvotes: 1

Views: 640

Answers (1)

user16135923
user16135923

Reputation:

Arrow functions are anonymous and will be re-instantiated on every render.

If you create a named component, it will have a reference and will not be re-rendered by React unless and until required (through state update).

And also, as you mentioned, it provides better readability and an option for code splitting.

Upvotes: 4

Related Questions