Components and Composition
10 min read
Building with Components
A React application is a tree of components. You compose complex UIs by nesting simpler ones — the same way you nest HTML elements. Each component is just a function that accepts an object of props and returns JSX.
jsx
function Avatar({ src, name }) {
return <img className="avatar" src={src} alt={name} />;
}
function ProfileCard({ user }) {
return (
<div className="card">
<Avatar src={user.photo} name={user.name} />
<h2>{user.name}</h2>
<p>{user.bio}</p>
</div>
);
}
function App() {
const user = { name: "Priya", photo: "/priya.jpg", bio: "Engineer" };
return <ProfileCard user={user} />;
}Thinking in components
A good heuristic: if a piece of UI appears more than once, or if it has enough complexity to deserve its own name, extract it into a component. Keep components small and focused on a single responsibility.
Co-locate a component with the file that uses it until it needs to be shared. Premature extraction into a shared components/ folder adds indirection without benefit.
Ready to test yourself?
Practice React— quiz & coding exercises