Components
1. Keep Components Pure
Components should be pure functions that only depend on their props and lens:
- ✅ Good - pure component
- ❌ Avoid - impure component
Pure Components
//
const UserCard = createComponent(({ lens, user, onEdit }) => {
const isExpanded = lens.useRefraction(false);
return (
<div className="user-card">
<h3>{user.name}</h3>
<button onClick={() => isExpanded.set(!isExpanded.value)}>
{isExpanded.value ? 'Collapse' : 'Expand'}
</button>
{isExpanded.value && (
<div>
<p>{user.email}</p>
<button onClick={() => onEdit(user)}>Edit</button>
</div>
)}
</div>
);
});
Impure Components
//
const UserCard = createComponent(({ lens, user, onEdit }) => {
const isExpanded = lens.useRefraction(false);
// ❌ Avoid - accessing external variables
const globalCounter = useRefraction(0);
return (
<div className="user-card">
<h3>{user.name}</h3>
<button onClick={() => isExpanded.set(!isExpanded.value)}>
{isExpanded.value ? 'Collapse' : 'Expand'}
</button>
{isExpanded.value && (
<div>
<p>{user.email}</p>
<button onClick={() => onEdit(user)}>Edit</button>
</div>
)}
</div>
);
});
2. Use Descriptive Names
Choose clear, descriptive names for your components:
- ✅ Good - descriptive names
- ❌ Avoid - vague names
Descriptive Names
// ✅ Good - descriptive names
const UserProfileCard = createComponent(({ lens, user }) => { /* ... */ });
const ShoppingCartSummary = createComponent(({ lens, items }) => { /* ... */ });
const NavigationMenu = createComponent(({ lens, items }) => { /* ... */ });
Vague Names
// ❌ Avoid - vague names
const Card = createComponent(({ lens, data }) => { /* ... */ });
const Component = createComponent(({ lens, props }) => { /* ... */ });
const Thing = createComponent(({ lens, stuff }) => { /* ... */ });
3. Organize Props Interface
Structure your props for clarity and maintainability:
- ✅ Good - clear prop structure
- ❌ Avoid - unclear prop structure
Clear Prop Structure
// ✅ Good - clear prop structure
const ProductCard = createComponent(({
lens,
product, // Main data
showPrice = true, // Configuration
onAddToCart, // Event handlers
onViewDetails
}) => {
// Component logic
});
Unclear Prop Structure
// ❌ Avoid - unclear prop structure
const ProductCard = createComponent(({
lens,
data,
show,
onAdd,
onView
}) => {
// Component logic
});
Related APIs
- useRefraction - Managing component state
- useEffect - Side effects and lifecycle
- useOptic - Custom logic patterns
- createApp - Creating applications