Avoid defining nested components in React
Do not define a component function inside another component function. When a component is defined inside another, the inner component is re-created on every render of the parent. This causes the inner component to be treated as a brand new component type, leading to complete unmounting and remounting of the subtree, which destroys local state and degrades performance.
Instead, define components at the top level (outside the parent) and pass necessary data via props.
// ❌ BAD: Nested components are re-created on every Parent render
function Parent(props) {
const [state, setState] = useState(props.initialData);
function Child1() {
return <div>Child1: {state}</div>;
}
return <Child1 />;
}
// ✅ GOOD: Components defined outside the parent
function Child1({ state }) {
return <div>Child1: {state}</div>;
}
function Parent(props) {
const [state, setState] = useState(props.initialData);
return <Child1 state={state} />;
}