Components & Composition
Components are self-contained, reusable building blocks that accept props and return JSX.
Mental Model
"LEGO Bricks: Small specialized bricks snap together to build castles, spaceships, or entire cities."
Interactive Engine Walkthrough
<Layout>
<Header>
<Logo />
<SearchBar />
</Header>
<Sidebar>
<NavMenu />
</Sidebar>
<Main>
<FeedList />
</Main>
</Layout>Put Logo in the header and the sidebar: one component, two instances, zero duplicated code. The layout never knows what it is holding — it only decides where its children go.
Reference Code Snippet
1function Button({ children }) {
2 return <button className="btn">{children}</button>;
3}
4
5function Card({ title, body }) {
6 return (
7 <div className="card">
8 <h3>{title}</h3>
9 <p>{body}</p>
10 <Button>Learn More</Button>
11 </div>
12 );
13}- 01.Prefer composition over inheritance using props.children and specialized slot props.
- 02.Components should adhere to the Single Responsibility Principle.
- 03.Keep components pure: given the same props, they should return the same JSX without side effects during render.
01. Thinking in Components
The genius of React is its **fractal** nature. You build a button, then a form, then a page, then an app. Each layer is just a component composed of smaller components. This allows for total **separation of concerns**—one developer can perfect the Button's accessibility while another builds the Login logic.
Isolation
Styles and logic don't leak out.
Reusability
Write once, use across the cosmos.
02. Composition vs Inheritance
React favors **Composition**. Instead of creating a `SpecialButton` class that inherits from `Button`, you pass `props.children` or specialized props to a generic `Button` component. This "has-a" relationship is much more flexible than the "is-a" relationship found in traditional OOP.
Architectural Advice
"If a component is getting too large (over 200 lines), it's a sign that it should be broken down into smaller sub-components. Aim for components that do one thing and do it perfectly."