Home / Learn React / Components: The Building Blocks
Components: The Building Blocks
A component is a JavaScript function that returns JSX. You build a page by putting components inside other components, like building with blocks.
Theory in plain words
What it is
A component is a reusable piece of UI. In modern React it is a plain function. It can use other components inside its JSX, so a whole app is a tree of components.
Why we use it
Components let you write something once and use it many times, test it alone, and change it in one place. Big screens become small, easy to understand pieces.
How it works
React calls your function and uses the JSX it returns. A capital letter tells React that <Card /> is your component and not an HTML tag such as <div>. Each use of <Card /> gets its own props and its own state.
Where it is used
- Buttons, cards, navbars, modals and forms
- Whole pages and layouts
- List items such as products, comments and messages
- Anything you want to reuse
Write and use a component
Add a third <Welcome /> and run again.
Naming rules
- A component name must start with a capital letter:
ProfileCard, notprofileCard. - Use one component per job. If a function is more than about 50 lines of JSX, think about splitting it.
- Define components at the top level of a file. Never define a component inside another component: it is recreated on every render and loses its state.
Components with different looks: props
Two copies of the same component usually show different data. That data arrives through props. You will learn them in the next lesson.
Files and exports
// Card.jsx
export default function Card() {
return <div className="card">Hello</div>;
}
// App.jsx
import Card from "./Card.jsx";
export default function App() {
return <Card />;
}In a real project each component usually has its own file. export default lets you import it with any name. A named export (export function Card) must be imported with braces: import { Card } from "./Card.jsx".
class X extends React.Component) still work but new code uses function components and hooks. The only thing that still needs a class is an old style error boundary.<Card />, not Card(). Calling it directly breaks hooks and state.Quick quiz
1. A component name must start with...
Lowercase names are treated as HTML tags.
2. How should you use a component?
Use it like a tag. Calling it as a function breaks hooks.
3. Why not define a component inside another component?
A new function identity each render makes React treat it as a different component.
Common questions
How should you use a component?
<Card />. Use it like a tag. Calling it as a function breaks hooks.
Why not define a component inside another component?
It is recreated every render and loses its state. A new function identity each render makes React treat it as a different component.