Skip to content

Support for custom event triggers in ComponentStates #3711

Open

Description

@TheRideout

I would like to be able to define custom event triggers inside a ComponentState that I can use to drive events in other states.

As an example using ReusableCounter, I define an event trigger called "on_over_ten" that I can pass a value through, and then emit this whenever the counter changes and the value is over 10. I then connect the trigger to a simple MyState "over_ten" event to execute something. Pseudocode without much understanding of how the system fundamentally works:

class ReusableCounter(rx.ComponentState):
    count: int = 0

    on_over_ten: lambda value: [value]??

    def increment(self):
        self.count += 1
        if self.count > 10:
            self.on_over_ten.emit(self.count)

    def decrement(self):
        self.count -= 1
        if self.count > 10:
            self.on_over_ten.emit(self.count)

    @classmethod
    def get_component(cls, **props):
        return rx.hstack(
            rx.button("Decrement", on_click=cls.decrement),
            rx.text(cls.count),
            rx.button("Increment", on_click=cls.increment),
            **props,
        )

reusable_counter = ReusableCounter.create

class MyState(rx.State):
    def over_ten(self, value):
        return rx.console_log(value)

def example():
    return rx.vstack(
        reusable_counter(on_over_ten=MyState.over_ten),
    )

Ultimately I think this could get us functionally closer to being able to build our own React components inside of Reflex.

Activity

  1. added
    feature request
    on Jul 29, 2024
  2. tsaipraveen99 commented on Aug 6, 2024

    @tsaipraveen99

    Hi, I would like to work on this. Could you please assign this to me?

  3. Alek99 commented on Aug 7, 2024

    @Alek99
    Member

    Hi, just assigned you to the other issue. Once that one is done I'll assign this to you if still unclaimed.

  4. bhngupta commented on Aug 7, 2024

    @bhngupta

    Hello @Alek99, I have gone through the reflex codebase and this seems like an interesting feature to hack on. I would like to take this up.

  5. TimChild commented on Aug 16, 2024

    @TimChild
    Contributor

    You can achieve roughly what you are aiming for by doing something like the code copied below. The main points being:

    • add a ClassVar that will hold the other event handlers you'd like to trigger
    • register the event handlers to the component .State after you call .create() to make the reusable component.
      • A new class is made every time .create is called, and is stored in the returned components .State attribute
      • Be careful about initializing the list of EventHandlers on the ComponentState... E.g. If you were to use a mutable object like a list, and only append to it when registering, all instances of the ComponentState will share the same on_increment_listener list.
    • return (or yield) the EventHander or list of EventHandlers from the ComponentState event handler method.

    The example below consists of two counters, where on one of them I have registered another event handler to listen to the increment method being called.

    from typing import ClassVar
    import reflex as rx
    
    from reflex_test.templates.template import template
    
    
    class Counter(rx.ComponentState):
        # Define vars that change.
        count: int = 0
    
        # Be careful about this being a mutable object.
        on_increment_listener: ClassVar[list[rx.EventHandler]] = None
    
        # Define event handlers.
        def increment(self) -> list[rx.EventHandler]:
            self.count += 1
            return self.on_increment_listener
    
        def decrement(self):
            self.count -= 1
    
        @classmethod
        def get_component(cls, **props):
            # Access the state vars and event handlers using `cls`.
            return rx.hstack(
                rx.button("Decrement", on_click=cls.decrement,
                          id="button-decrement"),
                rx.text(cls.count, id="counter-value"),
                rx.button("Increment", on_click=cls.increment,
                          id="button-increment"),
                **props,
            )
    
        @classmethod
        def register_listener(cls, event_handler: rx.EventHandler) -> None:
            if cls.on_increment_listener is None:
                cls.on_increment_listener = [event_handler]
            else:
                cls.on_increment_listener.append(event_handler)
    
    
    class OtherState(rx.State):
        value: int = 0
    
        def increment_when_counter_increments(self):
            self.value += 2
    
    
    @template(route="/counter_example", title="Counter example")
    def index() -> rx.Component:
        counter = Counter.create()
        other_component = rx.card(
            rx.vstack(rx.text("I only increment"), rx.text(OtherState.value)))
        counter.State.register_listener(
            OtherState.increment_when_counter_increments)
    
        counter_2 = Counter.create()
        return rx.container(
            rx.card(
                rx.hstack(
                    rx.text("The counter:"),
                    counter,
                ),
                rx.hstack(
                    rx.text(
                        "Some other component that updates when the counter increments"),
                    other_component,
                )
            ),
            rx.hstack(
                rx.text("Another counter that is separate"),
                counter_2,
            )
        )
    
  6. dyeruva1225545620 commented on Aug 27, 2024

    @dyeruva1225545620

    Hi, Could you assign this task to me, would love to work on it.

  7. picklelo commented on Aug 27, 2024

    @picklelo
    Contributor

    @dyeruva1225545620 just assigned you, let us know if you have issues, ComponentState is a bit tricky

  8. samarth9201 commented on Sep 14, 2024

    @samarth9201
    Contributor

    Hey, can I get assigned to this issue if no one is working on this?

  9. samarth9201 commented on Sep 17, 2024

    @samarth9201
    Contributor

    Hello,

    I would appreciate some guidance on this issue to ensure I'm understanding the task correctly. From my understanding, we need to implement functionality similar to React's useEffect. To approach this, I have developed the following proof of concept:

    class Effects:
    
        _tracked_vars = set()
    
        def __init__(self):
          """
            Initializes the Reactive StateManager with the following:
            - _tracked_vars: A set of state variables being monitored.
            - _effect_handlers: A dictionary mapping state variables to effect functions.
            - _pending_effects: A set of state variables whose effects are pending execution.
            - _batch_in_progress: A boolean flag indicating whether a batch of updates is in progress.
          """
          self._effect_handlers = {}
          self._pending_effects = set()
          self._batch_in_progress = False
    
        def __setattr__(self, name, value) -> None:
            """
            Overrides the default __setattr__ to trigger effects when a tracked variable changes.
    
            If a state variable (tracked variable) is updated and its value has changed:
            - If a batch is in progress, the change is added to _pending_effects.
            - Otherwise, the relevant effects are triggered immediately.
    
            Args:
                name (str): The name of the state variable.
                value: The new value to set for the state variable.
            """
            if name in self._tracked_vars:
                old_value = getattr(self, f"{name}", None)
                if old_value != value:
                    super().__setattr__(name, value)
                    if self._batch_in_progress:
                        self._pending_effects.add(name)
                    else:
                        self._trigger_effects(name)
            else:
                super().__setattr__(name, value)
    
        def register_effect(self, effect_fn, dependencies):
            """
            Registers an effect function that should be triggered whenever one of the dependent
            state variables changes.
    
            Args:
                effect_fn (callable): The effect function to be triggered.
                dependencies (list): List of state variables (as strings) that the effect depends on.
            """
            print(type(effect_fn))
            for var in dependencies:
                if var not in self._effect_handlers:
                    self._effect_handlers[var] = set()
                self._effect_handlers[var].add(effect_fn)
    
            for var in dependencies:
                self._tracked_vars.add(var)
    
        def _trigger_effects(self, var):
            """
            Executes all effect functions associated with the given state variable.
    
            Args:
                var (str): The name of the state variable whose effects are being triggered.
            """
            for effect_fn in self._effect_handlers.get(var, []):
                effect_fn()
    
        def apply_pending_effects(self):
            """
            Applies all pending effects that were queued during a batch update.
            This is called after a batch of updates is completed.
            """
            while self._pending_effects:
                var = self._pending_effects.pop()
                self._trigger_effects(var)
    
        def __getattribute__(self, name):
            """
            Overrides __getattribute__ to wrap callable methods in a batching mechanism.
    
            If a method is invoked, it checks if a batch is already in progress. If not,
            it starts a batch, calls the method, applies any pending effects, and then
            ends the batch.
    
            Args:
                name (str): The name of the attribute being accessed.
    
            Returns:
                The attribute, or a wrapped function if the attribute is callable.
            """
            attr = object.__getattribute__(self, name)  # Get the original attribute
    
            if callable(attr):  # Check if the attribute is callable (a method)
                def wrapper(*args, **kwargs):
                    if not getattr(self, '_batch_in_progress', False):
                        self._batch_in_progress = True
                        result = attr(*args, **kwargs)  # Call the original function
                        self.apply_pending_effects()
                        self._batch_in_progress = False
                    else:
                        result = attr(*args, **kwargs)  # Call the original function
                    return result
                return wrapper
            else:
                return attr
    
    

    The idea here is to check if state updates have occurred and execute the appropriate effect functions.

    Here’s an example of how this can be used:

    class ReusableCounter(Effects):
    
      def __init__(self):
        super().__init__()
        self.count = 0
    
        self.register_effect(self.on_over_ten, ['count'])
        self.register_effect(self.on_less_than_zero, ['count'])
    
      def increment(self):
        self.count += 1
    
      def decrement(self):
        self.count -= 1
    
      def on_over_ten(self):
        if self.count > 10:
          print("Greater than 10 : count = ", self.count)
    
      def on_less_than_zero(self):
        if self.count < 0:
          print("Value less than Zero, count = ", self.count)
    

    The code works as expected by detecting state changes and executing corresponding effect functions. However, I’m struggling with how to integrate this with Reflex state. I’m not entirely clear on how Reflex state management works, and I'm encountering errors when trying to inherit the Effects class within a Reflex component.

    Could you please review this implementation and provide any guidance on how to properly integrate it with Reflex?

    Thank you!

  10. picklelo commented on Sep 19, 2024

    @picklelo
    Contributor

    @samarth9201 great investigation, thanks for the work. For your class, wouldn't you need it to still subclass from ComponentState?

    The part where the event handler is actually run is over here in the process_event function. All it does though is call the event handler and get the delta afterwards. We could do the apply_pending_effects there but we are trying to keep the code modular and it would be better not to touch the main loop.

    I wonder if there's a way to wrap the event handler itself such that it calls apply_pending_effects after it's done. Maybe @masenf can give more insight on this, and if we want to bring this into our core (we will still pay out the bounty for the working solution regardless!)

  11. samarth9201 commented on Sep 19, 2024

    @samarth9201
    Contributor

    Thanks for the feedback, @picklelo!

    You're right, the class will inherit from ComponentState. My goal was to prototype the solution outside of Reflex first to ensure the concept works. I'll now look into how to integrate it properly while aligning with Reflex’s design principles.

    I'll dive deeper into how this can be done and make sure the solution remains modular. Any further insights or guidance would be greatly appreciated! 🙌

  12. davewat commented on Sep 26, 2024

    @davewat

    @TimChild From your example code (which works great, btw - thank you!):

    class OtherState(rx.State):
        value: int = 0
    
        def increment_when_counter_increments(self):
            self.value += 2
    

    Is it possible to pass additional values from the ComponentState to the EventHandler? Modified as:

    def increment_when_counter_increments(self,additional_value):
            self.value += 2
            print(additional_value)
    

    Thanks!

  13. TimChild commented on Sep 27, 2024

    @TimChild
    Contributor

    @davewat

    I haven't tried this, but I'd try going down this route:

    Have your states implement a protocol (this is mostly for static type checking, but might make the example more clear).

    class HasIncrement(Protocol):
        async def on_increment(self, counter_value: int) -> None: ...

    then modify the Counter.increment method like this

    class Counter(rx.ComponentState):
    	...
        on_increment_callable_listeners: ClassVar[list[type[rx.State]]] = None
    
    	# note: need async to do self.get_state(...)
        async def increment(self) -> list[rx.EventHandler]:
            self.count += 1
    
            if self.on_increment_callable_listeners:
                for state_cls in self.on_increment_callable_listeners:
                    state: HasIncrement = await self.get_state(state_cls)
                    state.on_increment(self.count)
    
            return self.on_increment_listener
    
    	...
    
        @classmethod
        def register_callable_listener(cls, state_cls: type[rx.State] | HasIncrement) -> None:
            assert issubclass(state_cls, rx.State)
            assert hasattr(state_cls, "on_increment")
            if cls.on_increment_callable_listeners is None:
                cls.on_increment_callable_listeners = [state_cls]
            else:
                cls.on_increment_callable_listeners.append(state_cls)

    Then you would register a whole state class like:

    class OnIncrementState(rx.State):
        doubled: int = 0
        
        def on_increment(self, counter_value: int):
            self.doubled = counter_value * 2
            
            
    counter.State.register_callable_listener(OtherState)
  14. hongwingl commented on Jun 16, 2025

    @hongwingl

    @TimChild From your example code (which works great, btw - thank you!):

    class OtherState(rx.State):
        value: int = 0
    
        def increment_when_counter_increments(self):
            self.value += 2
    

    Is it possible to pass additional values from the ComponentState to the EventHandler? Modified as:

    def increment_when_counter_increments(self,additional_value):
            self.value += 2
            print(additional_value)
    

    Thanks!

    If it is just one EventHandler, you can do this by returning the rx.EventHandler with the extra argument:

        # Define event handlers.
        def increment(self, additional_value) -> rx.EventHandler:
            self.count += 1
            return self.on_increment_listener(additional_value)
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions