'It's okay to declare other components inside a component?
Imagine that I have a List of Cards on my react application. So I will have two components, the <ListCard /> and <Card />.
My doubt is that where I work, when we have something like this, we usually declare a variable inside the <ListCard /> named Card that receives a JSX, but I don't know if this is a good thing to do. Recently I faced some problems with this approach, but I didn't find anyone saying to do it or not.
Imagine that I'm not using the <Card /> anywhere in the application
The way we would declare the ListCard
const ListCard = () => {
const cards = [
{ title: '1', id: 1 },
{ title: '2', id: 2 },
];
const Card = ({ title }) => <div>{title}</div>;
return (
<div>
<h1>List of Cards</h1>
{cards.map(card => (
<Card title={card.title} key={card.id} />
))}
</div>
);
};
I want to know if it's better to declare outside of the ListCard, like this.
const Card = ({ title }) => <div>{title}</div>;
const ListCard = () => {
const cards = [
{ title: '1', id: 1 },
{ title: '2', id: 2 },
];
return (
<div>
<h1>List of Cards</h1>
{cards.map(card => (
<Card title={card.title} key={card.id} />
))}
</div>
);
};
Solution 1:[1]
It is totally fine to declare another Component in the same file, but declaring it inside another one's function would be inefficient. Imagine your app 'recreating' the second Component during each render.
So, feel free to declare it in the same file, but don't do it inside another Component's function.
Solution 2:[2]
In a functional component, every variable gets destroyed and recreated again every render. This is what makes the useState hook so valuable, as it is smart enough to recreate it's variables with the previous or updated values.
By declaring a component inside another component, you are not only re-rendering both components, but completely redeclaring one. This won't be very performant, especially if the component is more complex.
So the answer to your question is always declare it separate. It would work declared inside, but there's no benefits from it, only drawbacks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | don_jon |
| Solution 2 | Brian Thompson |
