Browse Source

[Beta] Don't nest components (#5132)

main
dan 2 years ago
committed by GitHub
parent
commit
f75d0e2518
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 31
      beta/src/content/learn/your-first-component.md

31
beta/src/content/learn/your-first-component.md

@ -176,6 +176,37 @@ Components are regular JavaScript functions, so you can keep multiple components
Because the `Profile` components are rendered inside `Gallery`—even several times!—we can say that `Gallery` is a **parent component,** rendering each `Profile` as a "child". This is part of the magic of React: you can define a component once, and then use it in as many places and as many times as you like. Because the `Profile` components are rendered inside `Gallery`—even several times!—we can say that `Gallery` is a **parent component,** rendering each `Profile` as a "child". This is part of the magic of React: you can define a component once, and then use it in as many places and as many times as you like.
<Gotcha>
Components can render other components, but **you must never nest their definitions:**
```js {2-5}
export default function Gallery() {
// 🔴 Never define a component inside another component!
function Profile() {
// ...
}
// ...
}
```
The snippet above is [very slow and causes bugs.](/learn/preserving-and-resetting-state#different-components-at-the-same-position-reset-state) Instead, define every component at the top level:
```js {5-8}
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](/learn/passing-props-to-a-component) instead of nesting definitions.
</Gotcha>
<DeepDive title="Components all the way down"> <DeepDive title="Components all the way down">
Your React application begins at a "root" component. Usually, it is created automatically when you start a new project. For example, if you use [CodeSandbox](https://codesandbox.io/) or [Create React App](https://create-react-app.dev/), the root component is defined in `src/App.js`. If you use the framework [Next.js](https://nextjs.org/), the root component is defined in `pages/index.js`. In these examples, you've been exporting root components. Your React application begins at a "root" component. Usually, it is created automatically when you start a new project. For example, if you use [CodeSandbox](https://codesandbox.io/) or [Create React App](https://create-react-app.dev/), the root component is defined in `src/App.js`. If you use the framework [Next.js](https://nextjs.org/), the root component is defined in `pages/index.js`. In these examples, you've been exporting root components.

Loading…
Cancel
Save