Skip to content

Instantly share code, notes, and snippets.

@drumnickydrum
Last active January 30, 2023 15:51
Show Gist options
  • Save drumnickydrum/99959f7e7a5d7e4e4bcd6b4efc098b35 to your computer and use it in GitHub Desktop.
Save drumnickydrum/99959f7e7a5d7e4e4bcd6b4efc098b35 to your computer and use it in GitHub Desktop.
[React: Don't nest component definitions] React docs warning about nested component definitions #react #components #nesting

https://beta.reactjs.org/learn/your-first-component#nesting-and-organizing-components

Components can render other components, but you must never nest their definitions:

export default function Gallery() {
  // 🔴 Never define a component inside another component!
  function Profile() {
    // ...
  }
  // ...
}

The snippet above is very slow and causes bugs. Instead, define every component at the top level:

export default function Gallery() {
  // ...
}

// ✅ Declare components at the top level
function Profile() {
  // ...
}

When a child component needs some data from a parent, pass it by props instead of nesting definitions.

Position in the render tree

https://beta.reactjs.org/learn/preserving-and-resetting-state#different-components-at-the-same-position-reset-state

When nesting component function definition, you’re rendering a different component (redefined on render) in the same position, so React resets all state below. This leads to bugs and performance problems. To avoid this problem, always declare component functions at the top level, and don’t nest their definitions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment