Mastering State Management with djust Decorators
Introduction
One of djust's most powerful features is its collection of state management decorators. These decorators let you control how your application handles user interactions, making it easy to build responsive UIs without complex JavaScript.
The @debounce Decorator
The @debounce decorator delays server requests until the user stops typing. Perfect for search inputs:
from djust import LiveView, debounce
class SearchView(LiveView):
template_name = "search.html"
def mount(self, request):
self.query = ""
self.results = []
@debounce(wait=0.5)
def search(self, query):
self.query = query
self.results = Product.objects.filter(name__icontains=query)[:10]
The @optimistic Decorator
The @optimistic decorator updates the UI instantly, then validates on the server. Zero perceived latency:
from djust import LiveView, optimistic
class LikeButton(LiveView):
@optimistic
def toggle_like(self):
self.liked = not self.liked
# Server validates and persists
The @cache Decorator
Cache responses client-side for instant results on repeated queries:
from djust import LiveView, cache
class CitySelector(LiveView):
@cache(ttl=300) # Cache for 5 minutes
def get_cities(self, country):
return City.objects.filter(country=country)
The @client_state Decorator
Sync state across multiple components without server roundtrips:
from djust import LiveView, client_state
class TabPanel(LiveView):
@client_state(keys=["active_tab"])
def switch_tab(self, tab):
self.active_tab = tab
Conclusion
These decorators are just the beginning. Combine them to create complex, responsive interfaces while keeping all your logic in Python.
Related Posts
Faster Templates, Smarter Hydration: Performance Optimizations in djust 0.1.6
djust 0.1.6 introduces AST optimization for 5-15% faster rendering, lazy hydration for 20-40% memory reduction, TurboNav integration, and improved whitespace preservation.
Full Django Template Compatibility: URL Tags, Comparison Operators, and Auto-Serialization
djust v0.1.6 brings major template system improvements including {% url %} tag support, {% include %} fixes, comparison operators in {% if %} conditions, and automatic Django type serialization.
Security-First Development: How djust Protects Your Application by Default
djust now includes built-in security utilities, automated vulnerability scanning, and pre-commit hooks to help you build secure applications from day one. Here's what's new in PR #40.