What are React Components?
Components are the building blocks of React applications. They encapsulate UI logic and rendering, making code reusable and maintainable. Components accept inputs called props and return React elements describing what should appear on screen.
Functional Components
Class Components
Functional vs Class Components
| Feature | Functional | Class | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| State | useState hook | this.state | |||||||||||
| Lifecycle | useEffect hook | componentDidMount, etc. | |||||||||||
| Code complexity | Simple and concise | More verbose | |||||||||||
| Performance | Slightly better | Slightly slower | |||||||||||
| L | e | a | r | n | i | n | g | c | u | r | v | e | |
| E | a | s | i | e | r | ||||||||
| S | t | e | e | p | e | r | |||||||
| Current trend | ✅ Recommended | Legacy (still valid) |
Component Composition
Pure Components & React.memo
Higher-Order Components (HOC)
Render Props Component
Compound Components
Controlled vs Uncontrolled Components
Component Best Practices
- Single responsibility – Each component should do one thing well
- Keep components small – Aim for < 200 lines per component
- Use meaningful names – Component names should describe what they do
- Props should be minimal – Only pass what the component needs
- Use composition over inheritance – React has a powerful composition model
- Extract reusable logic – Use custom hooks instead of HOCs
- Memoize when necessary – Use React.memo for expensive components
- Keep components pure – Same props should produce same output
- Colocate related files – Keep styles, tests with components
- Document components – Use PropTypes, TypeScript, or comments
Common Component Patterns
| Pattern | Use Case | Example |
|---|---|---|
| Container/Presentational | Separate logic from UI | useFetch hook + Display component |
| Compound Components | Related components that work together | Tabs, Accordion, Menu |
| Render Props | Share code between components | Mouse tracker, Data fetcher |
| Higher-Order Components | Cross-cutting concerns | Authentication, Logging |
| Controlled Components | Form inputs with parent state | Input, Select, Checkbox |
| Custom Hooks | Reusable stateful logic | useFetch, useLocalStorage |
Conclusion
React components are powerful building blocks for UI development. Start with functional components and hooks for new projects. Use composition to build complex UIs from simple pieces. Choose patterns like HOCs, render props, or custom hooks based on your specific needs.