Reputation: 663
When should I create a new React component, as opposed to defining a helper function in the same one?
In tutorials I usually see components like "StuffList" being defined that way:
StuffList = ({ list }) => {
const renderItem = item => {
return <div>{item}</div>
}
return list.map(item => renderItem(item))
}
The example above is really simple, but for both the list and the item the complexity can creep up quite a bit. So, I wonder what would be a good indicator that Item deserves to be extracted into it's own component? I'm not only talking about lists and items too, it's just the simplest example that came to mind.
Upvotes: 6
Views: 5927
Reputation: 991
As you might have guessed it depends. However, extracting a new component from an existing one can be considered to be a variation of the Extract Function refactoring. To paraphrase Martin Fowler from the highly recommended Refactoring book on when to use this refactoring:
If you have to spend effort looking at a fragment of code and figuring out what it's doing, then you should extract it into a
functioncomponent and name thefunctioncomponent after the "what."
Other potential benefits here are being able to reuse the new component, reducing the original component's size (i.e. lines of code), and in the case of React it may help with rendering performance.
Edit: Also see this post by Kent C Dodds When to break up components into multiple components for another perspective.
Upvotes: 3