11

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 enter image description here

Tholle
  • 108,070
  • 19
  • 198
  • 189
taile
  • 2,738
  • 17
  • 29
  • I understand that you are just experimenting, but are you saying that the entire list is not updated in the DOM if you define the `Todo` component outside of `TodoList`? – Tholle Aug 05 '18 at 16:51
  • 1
    Yes. I noticed it just add the new one todo into the list – taile Aug 05 '18 at 16:52

1 Answers1

8

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.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151