Home Features Docs Blog Security Examples Quick Start

Mastering State Management with djust Decorators

djust Team | | 1 min read
Concentric circles representing state layers and decorator patterns

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.

Share this post

Related Posts