React · Middle · Question 6 of 75

Why shouldn't you declare a component inside another component?

function Page() {
  function Row({ item }) { return <li>{item}</li>; }
  return <ul>{items.map(i => <Row key={i} item={i} />)}</ul>;
}

Explanation

To React, Row from different renders are different component types, since they're new functions. So the subtree unmounts and remounts every time: state and focus are lost, and the DOM is recreated. Declare components at the top level of the module.

Further reading

Problem with a question

React · Middle · question 6

Test yourself

Take the React · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz