React Components
Building reusable UI pieces with React components and props
What you'll learn
Build reusable function components with TypeScript props
Compose components by nesting children with the children prop
Pass event handlers and render props for flexible APIs
Use React.memo to prevent unnecessary re-renders
Control component rendering with conditional patterns
Split large components into smaller, focused pieces
Components are the building blocks of any React application. They let you split the UI into independent, reusable pieces.
Function Components
Modern React uses function components:
interface GreetingProps {
name: string
age?: number
}
function Greeting({ name, age }: GreetingProps) {
return (
<div>
<h1>Hello, {name}!</h1>
{age && <p>Age: {age}</p>}
</div>
)
}
Props
Props (properties) are read-only inputs to components:
interface ButtonProps {
variant: "primary" | "secondary"
children: React.ReactNode
onClick?: () => void
disabled?: boolean
}
function Button({ variant, children, onClick, disabled }: ButtonProps) {
const base = "rounded px-4 py-2 font-medium"
const styles = {
primary: "bg-blue-500 text-white",
secondary: "bg-gray-200 text-gray-800",
}
return (
<button
className={`${base} ${styles[variant]}`}
onClick={onClick}
disabled={disabled}
>
{children}
</button>
)
}
Composition
React encourages component composition over inheritance:
function Card({
title,
children,
}: {
title: string
children: React.ReactNode
}) {
return (
<div className="rounded-lg border p-4 shadow-sm">
<h2 className="mb-2 text-lg font-semibold">{title}</h2>
{children}
</div>
)
}
// Usage
;<Card title="Welcome">
<p>Card content goes here.</p>
<Button variant="primary">Learn More</Button>
</Card>
Best Practices
- Keep components focused on a single responsibility
- Use TypeScript interfaces for props
- Prefer composition over prop drilling
- Extract reusable logic into custom hooks
- Use
childrenfor flexible content areas
Next Steps
- React Hooks — useState and other hooks
- State Management — Manage complex state
Key Takeaways
Function components with typed props (TypeScript interfaces) are the standard React component pattern
The children prop enables component composition for wrappers, layouts, and generic containers
React.memo prevents re-renders when props haven't changed — use it as a performance optimization, not a default
Conditional rendering with &&, ternary, or if/else controls which components appear in the tree
Component decomposition (splitting large components) improves readability, testability, and reusability