Chapter 12: React Architecture Patterns
Chapter 12 of 15
Chapter 12: React Architecture Patterns
12.1 Component Organization
Well-organized code structure is crucial for maintainable React applications.
// Recommended folder structure
src/
├── components/ # Reusable components
│ ├── ui/ # Basic UI components
│ ├── forms/ # Form components
│ └── layout/ # Layout components
├── features/ # Feature-based organization
│ ├── auth/
│ │ ├── components/
│ │ ├── hooks/
│ │ └── utils/
│ └── dashboard/
├── hooks/ # Shared custom hooks
├── utils/ # Utility functions
├── services/ # API services
├── store/ # State management
└── types/ # TypeScript types
12.2 Feature-Based Architecture
// Organize by features, not by file type
features/
auth/
components/
LoginForm.tsx
SignupForm.tsx
hooks/
useAuth.ts
services/
authService.ts
types.ts
index.ts
12.3 Container/Presentational Pattern
// Container component (logic)
function UserListContainer() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchUsers().then(data => {
setUsers(data);
setLoading(false);
});
}, []);
return <UserList users={users} loading={loading} />;
}
// Presentational component (UI)
function UserList({ users, loading }) {
if (loading) return <div>Loading...</div>;
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
12.4 Compound Components Pattern
// Components that work together
const Select = ({ children, value, onChange }) => {
const [isOpen, setIsOpen] = useState(false);
return (
<SelectContext.Provider value={{ value, onChange, isOpen, setIsOpen }}>
{children}
</SelectContext.Provider>
);
};
Select.Option = ({ value, children }) => {
const { value: selected, onChange, setIsOpen } = useContext(SelectContext);
return (
<div
onClick={() => {
onChange(value);
setIsOpen(false);
}}
className={selected === value ? 'selected' : ""}
>
{children}
</div>
);
};
// Usage
<Select value={selected} onChange={setSelected}>
<Select.Option value="1">Option 1</Select.Option>
<Select.Option value="2">Option 2</Select.Option>
</Select>