I have read about the nested component in React.
I tried with this example and noticed that each time I updated the state of the parent component (todolist). The DOM tree re-render the whole instead of add new.
My question is: Is it an anti-pattern that we should avoid?
const TodoList = ({ todos, onTodoClick }) => {
const Todo = ({ completed, text, onClick }) => {
return (
<li onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }}>
{text}
</li>
);
};
return todos.map(todo => <Todo key={todo.id} {...todo} onClick={() => onTodoClick(todo.id)} />);
};
Here is my testing
The problem is, that when you call TodoList
twice, you will get two different closured versions of Todo
, that means that React will think that you are returning different components as the references to the constructor are not equal:
function TodoList() {
return function Todo() { }
}
console.log(TodoList() === TodoList()); // false
Is that a bad practice?
Moving Todo outside of TodoList is definetly performance wise as React can reconciliate better, however you loose the benefits of the closure. As you do not closure anything here, I would move it outside, but thats rather a question of preference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With