Production Patterns
Production-ready patterns with live, editable code examples
Polling & Auto-Refresh
PerformanceAutomatically update data at regular intervals
// Polling Pattern
const { div, h3, p } = van.tags;
// State
const status = van.state({
users: Math.floor(Math.random() * 100) + 50,
active: Math.floor(Math.random() * 30) + 10,
lastUpdate: new Date().toLocaleTimeString()
});
const isPolling = van.state(true);
// Poll for updates
let pollInterval = setInterval(() => {
if (isPolling.val) {
status.val = {
users: Math.floor(Math.random() * 100) + 50,
active: Math.floor(Math.random() * 30) + 10,
lastUpdate: new Date().toLocaleTimeString()
};
}
}, 3000); // Update every 3 seconds
// Toggle polling
const togglePolling = () => {
isPolling.val = !isPolling.val;
};
return div(
{ class: 'space-y-4' },
h3({ class: 'text-lg font-semibold mb-2' }, 'Polling Pattern'),
div({ class: 'flex gap-2 items-center mb-4' },
Button({
class: () => isPolling.val ? 'subtle vwfcolor-error vwfsize-sm' : 'subtle vwfcolor-success vwfsize-sm',
onclick: togglePolling
}, () => isPolling.val ? 'Stop Polling' : 'Start Polling'),
() => isPolling.val ? Badge({ class: 'subtle vwfcolor-success vwfsize-xs' }, '● Live') : ''
),
Card({ class: 'p-4 bg-white space-y-3' },
div({ class: 'flex justify-between items-center' },
div(
p({ class: 'text-sm text-secondary' }, 'Total Users'),
p({ class: 'text-2xl font-bold' }, () => status.val.users)
),
div(
p({ class: 'text-sm text-secondary' }, 'Active Now'),
p({ class: 'text-2xl font-bold text-success' }, () => status.val.active)
)
),
p({ class: 'text-xs text-secondary pt-3 border-t border-mist' },
'Last updated: ', () => status.val.lastUpdate
)
),
p({ class: 'text-xs text-secondary' },
'Updates every 3 seconds when polling is enabled'
)
);▶️ Live Preview
Polling Pattern
Total Users
146
Active Now
29
Last updated: 3:59:08 PM
Updates every 3 seconds when polling is enabled
💡 Click "Edit Code" to modify the example
🔄 Click "Apply Changes" to see your modifications
↩️ Click "Reset" to restore original code
📋 Best Practices
State Management
• Use individual van.state() for each value
• Keep state close to where it's used
• Update arrays immutably with spread operator
• Use arrow functions for reactive values
Performance
• Debounce expensive operations
• Use keys for list items
• Avoid complex computations in render
• Clean up timers and listeners
Component Design
• Accept both props and children
• Use parseArgs for flexibility
• Provide sensible defaults
• Keep components focused
User Experience
• Show loading states
• Provide immediate feedback
• Handle errors gracefully
• Add smooth transitions