You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Components are the fundamental building blocks of a React application. A component is a reusable, self-contained piece of UI that accepts inputs (called props) and returns JSX describing what should appear on screen.
Modern React uses function components — plain JavaScript functions that return JSX:
function Welcome({ name }) {
return <h1>Hello, {name}!</h1>;
}
Component names must start with a capital letter so React can distinguish them from plain HTML elements. would be treated as an unknown HTML tag; is a React component.
The real power of components is composition — building complex UIs by combining simpler components:
function Avatar({ src, alt }) {
return <img src={src} alt={alt} className="avatar" />;
}
function UserCard({ user }) {
return (
<div className="card">
<Avatar src={user.avatarUrl} alt={user.name} />
<p>{user.name}</p>
</div>
);
}
function App() {
const user = { name: "Alice", avatarUrl: "/alice.jpg" };
return <UserCard user={user} />;
}
Each component is responsible for a single piece of the UI, making the code easier to understand, test, and reuse.
Every React application has a root component (often called App) that contains other components, which in turn contain more components. This forms a tree structure that mirrors the UI hierarchy. React renders the tree top-down, passing data through props.
React expects components to be pure functions with respect to their props — given the same props, a component should always return the same JSX. Side effects (network requests, subscriptions, timers) should not happen during rendering; they belong in useEffect (covered in a later lesson).
A good rule of thumb: if a piece of JSX is used more than once, or if a section of a component becomes complex enough that it is hard to read, extract it into its own component. Components can be as small as a single button or as large as a full page section.
function Button({ label, onClick }) {
return (
<button onClick={onClick} className="btn">
{label}
</button>
);
}
Components are typically placed in their own files and exported. You can use either default exports or named exports:
// Button.jsx
export default function Button({ label, onClick }) {
return <button onClick={onClick}>{label}</button>;
}
// App.jsx
import Button from "./Button";
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.