1. Introduction đ
Components are the fundamental building blocks of every React application. They let you split complex user interfaces into small, independent, and reusable pieces. This tutorial explores what components are, how to create and organize them, and the design principles that separate maintainable React code from tangled, hard-to-follow code.
Information
2. What are Components? đ¤
A component is a self-contained, reusable piece of UI. Technically, it's just a JavaScript function that accepts inputs (called props) and returns JSX describing what should appear on screen.
Code Snippet
function Welcome() {
return <h1>Hello, welcome to React! đ</h1>;
}3. Why Components? đĄ
- Reusability: Write a piece of UI once and reuse it across your application.
- Maintainability: Isolated components are easier to debug, test, and update.
- Composability: Small components combine to build complex interfaces.
- Separation of Concerns: Each component can encapsulate its own logic, markup, and (optionally) styles.
- Collaboration: Teams can work on different components independently without conflicts.
4. Types of Components đī¸
Modern React development revolves almost entirely around function components. Legacy class components still exist in older codebases but are no longer recommended for new code.
| Type | Status | Description |
|---|---|---|
| Function Components | Recommended | Plain JavaScript functions returning JSX, using Hooks for state and lifecycle. |
| Class Components | Legacy | ES6 classes extending React.Component, using lifecycle methods. |
Best Practice
5. Function Components âī¸
A function component is simply a JavaScript function that returns JSX. Its name must start with a capital letter so React can distinguish it from a regular HTML tag.
Code Snippet
function ProfileCard({ name, role }) {
return (
<div className="profile-card">
<h2>{name}</h2>
<p>{role}</p>
</div>
);
}- Accepts a single props object as its argument.
- Must return JSX, null, or an array of elements.
- Can use Hooks like useState and useEffect internally.
6. Creating Your First Component đŦ
Greeting.jsx
function Greeting({ name }) {
return <h1>Hello, {name}! đ</h1>;
}
export default Greeting;App.jsx
import Greeting from './Greeting';
function App() {
return (
<div>
<Greeting name="Alice" />
</div>
);
}
export default App;Tip
7. Rendering Components đŧī¸
To render a component, use it like a custom JSX tag. React calls the function, evaluates the returned JSX, and inserts the result into the DOM.
Code Snippet
function App() {
return (
<div>
<Greeting name="Bob" />
<Greeting name="Carol" />
<Greeting name="Dave" />
</div>
);
}Note
8. Naming Components đˇī¸
- Component names must start with an uppercase letter (e.g., UserCard, not userCard).
- React treats lowercase tags as built-in HTML elements (e.g., div, span).
- Use PascalCase consistently for component names and their file names.
- Choose descriptive, specific names (e.g., UserAvatar over Avatar1).
Important
9. Importing Components đĨ
Code Snippet
// Named export
import { Header } from './Header';
// Default export
import Footer from './Footer';
// Importing multiple components
import { Button, Input, Card } from './ui-components';Tip
10. Exporting Components đ¤
Code Snippet
function Header() {
return <header>My App</header>;
}
export default Header;Use default exports when a file exports a single, primary component.
Code Snippet
export function Button({ label }) {
return <button>{label}</button>;
}
export function IconButton({ icon }) {
return <button>{icon}</button>;
}Use named exports when a file exports multiple related components.
11. Nested Components đĒ
Components can render other components inside their JSX, forming a tree of nested UI pieces.
Code Snippet
function Avatar({ src }) {
return <img className="avatar" src={src} alt="User avatar" />;
}
function UserCard({ user }) {
return (
<div className="user-card">
<Avatar src={user.avatarUrl} />
<h3>{user.name}</h3>
</div>
);
}Caution
12. Reusable Components âģī¸
Well-designed components accept props to customize their behavior and appearance, allowing the same component to be reused in many different contexts.
Code Snippet
function Button({ label, variant = "primary", onClick }) {
return (
<button className={`btn btn-${variant}`} onClick={onClick}>
{label}
</button>
);
}
// Reused with different props
<Button label="Save" variant="primary" onClick={handleSave} />
<Button label="Cancel" variant="secondary" onClick={handleCancel} />
<Button label="Delete" variant="danger" onClick={handleDelete} />13. Component Composition đī¸
Composition is the practice of building complex UIs by combining smaller components, often passing components as children rather than hardcoding structure.
Code Snippet
function Card({ children }) {
return <div className="card">{children}</div>;
}
function App() {
return (
<Card>
<h2>Card Title</h2>
<p>Card content goes here.</p>
</Card>
);
}Best Practice
14. Splitting UI into Components đĒ
Breaking a large interface into components involves identifying logical, reusable boundaries in the UI.
Tip
15. Root Component đŗ
The root component (commonly App) sits at the top of the component tree and is the entry point rendered into the DOM.
main.jsx
import { createRoot } from 'react-dom/client';
import App from './App';
createRoot(document.getElementById('root')).render(<App />);16. Parent Components đĒ
A parent component renders other components inside it and typically manages shared state or data passed down to its children via props.
Code Snippet
function TodoApp() {
const todos = ["Learn React", "Build a project"];
return (
<div>
<h1>My Todos</h1>
<TodoList todos={todos} />
</div>
);
}17. Child Components đļ
A child component receives data from its parent through props and typically has no knowledge of where that data originates.
Code Snippet
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo}>{todo}</li>
))}
</ul>
);
}Note
18. Component Hierarchy đ˛
React applications form a tree structure, where each component may have zero or more child components, all rooted at the top-level App component.
Information
19. Organizing Components đī¸
As applications grow, a clear folder structure keeps components discoverable and maintainable.
Tip
20. Single Responsibility Principle đ¯
Each component should ideally do one thing well. A component handling data fetching, complex business logic, and detailed presentation all at once quickly becomes difficult to test and reuse.
Before: One Component Doing Too Much
function UserDashboard() {
// fetching logic, formatting logic, and rendering
// all mixed together in one large component
// ...
}After: Split by Responsibility
function UserDashboard() {
const { user, loading } = useUser();
if (loading) return <Spinner />;
return <UserProfile user={user} />;
}21. Presentational Components đ¨
Presentational components focus purely on how things look. They receive data via props and render UI, without containing business logic or data-fetching code.
Code Snippet
function PriceTag({ amount, currency }) {
return (
<span className="price-tag">
{currency}{amount.toFixed(2)}
</span>
);
}22. Container Components đĻ
Container components handle how things work â managing state, fetching data, and passing it down to presentational components.
Code Snippet
function ProductPriceContainer({ productId }) {
const [price, setPrice] = useState(null);
useEffect(() => {
fetchPrice(productId).then(setPrice);
}, [productId]);
if (price === null) return <Spinner />;
return <PriceTag amount={price} currency="$" />;
}Note
23. Generic Components đ§Ŧ
Generic components are highly reusable, unopinionated building blocks (like buttons, modals, or inputs) that adapt to many contexts through flexible props.
Code Snippet
function Modal({ isOpen, onClose, children }) {
if (!isOpen) return null;
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content" onClick={(e) => e.stopPropagation()}>
{children}
</div>
</div>
);
}Best Practice
24. Component Communication Overview đĄ
Components communicate with each other in a few well-defined ways within React's unidirectional data flow model.
| Pattern | Direction | Mechanism |
|---|---|---|
| Parent â Child | Downward | Props |
| Child â Parent | Upward | Callback functions passed as props |
| Sibling â Sibling | Indirect | Lifted state in a common parent |
| Deeply Nested | Any level | Context API |
Reference
25. Component Lifecycle Overview âŗ
Every component goes through a lifecycle: it mounts (is created and inserted), updates (re-renders in response to state or prop changes), and eventually unmounts (is removed).
Information
26. Component Best Practices đ
- Keep components small and focused on a single responsibility.
- Name components with PascalCase and descriptive, specific names.
- Never define a component inside another component's function body.
- Favor composition using children over rigid, hardcoded structures.
- Extract reusable UI patterns into generic, prop-driven components.
- Colocate a component's styles and tests with its file when practical.
27. Common Component Mistakes đĢ
- Defining components with a lowercase name, causing React to treat them as HTML tags.
- Nesting component definitions inside other components, causing state loss on every render.
- Creating overly large "god" components that handle too many responsibilities at once.
- Duplicating logic across components instead of extracting a shared, reusable component.
- Forgetting to pass a key when rendering a list of components.
Danger
28. Frequently Asked Questions â
Question
Answer
Question
Answer
Question
Answer
29. Summary đ
Components are the core unit of reuse and organization in React. By breaking interfaces into small, focused pieces â following principles like single responsibility and composition â you create applications that are easier to build, test, and maintain over time.