Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React anti pattern, defined a component inside the definition of another component

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

like image 717
taile Avatar asked Aug 05 '18 16:08

taile


1 Answers

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.

like image 182
Jonas Wilms Avatar answered Oct 19 '22 14:10

Jonas Wilms