Components
Components are independent, reusable pieces of UI. Each component returns JSX describing a part of the interface.
Function Components
The modern way to write React components:
function Greeting() {
return <h1>Hello, World!</h1>;
}
Use PascalCase for component names. The name must start with a capital letter.
Rendering a Component
Use the component as a JSX tag:
function App() {
return (
<div>
<Greeting />
<Greeting />
</div>
);
}
Each <Greeting /> renders independently.
Composing Components
Components can nest and compose freely:
function Header() {
return <h1>My App</h1>;
}
function Content() {
return <p>Welcome to React.</p>;
}
function App() {
return (
<div>
<Header />
<Content />
</div>
);
}
Build complex UIs from small, focused pieces.
Component Tree
React renders components as a tree. App is the root, with children branching down:
App
├── Header
├── Content
└── Footer
Each component manages its own piece of the tree.
One Component Per File
Keep components in separate files:
src/
components/
Header.jsx
Footer.jsx
App.jsx
This keeps code organized and easy to find.
Best Practices
- Name components PascalCase —
UserProfile, notuserProfile - Keep components small — One job per component
- Extract when复用 occurs — If you copy-paste, make a component
- One component per file — Easier to navigate and maintain
Common Mistakes
- Lowercase component names —
<greeting />is treated as an HTML tag - Making components too large — Split into smaller pieces
- Putting everything in App.jsx — Extract to separate files
- Forgetting to export — Component won’t be importable