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
djust 0.2.2: The Debug Panel Gets Real
djust 0.2.2 transforms the debug panel from a static inspector into a live development companion. Event filtering, replay, network inspection, VDOM patch tracing, and live state updates via WebSocket — all wired up and working out of the box.
djust 0.2.1: WebSocket Security Hardening with Three Layers of Defense
djust 0.2.1 locks down WebSocket event dispatch with an event name guard, @event_handler decorator allowlist, server-side rate limiting, and per-IP connection tracking. A security-focused release with zero new features to break.
58 Ways to Break a VDOM (and Why Ours Didn't)
We wrote 58 torture tests targeting every weak spot in djust's virtual DOM diff engine: 50-level deep trees, 500-sibling lists, keyed shuffles, duplicate keys, and rapid-fire state updates. Everything passed. Here's what we tested, what we found, and why it matters.