Updating Component ID?

So I was playing around with updating component ID’s (not sure if that’s bad practice or not, but figured I could update the component ID, then when it’s called, just fetch the information from the callback context triggered id… basically using it as a temporary store). Now all of that being said, I’m really not sure that I understand why the following seems to work?

import dash_mantine_components as dmc

from dash import Dash, Input, Output, callback, html, Patch

app = Dash(__name__)

def create_layout():
    return dmc.Stack(
        [
        html.Div(id = {"component": "test", "index": 0}),
        dmc.Button(id="test3", n_clicks = 0),
        html.Div(id="id-test")
        ]
    )

app.layout = create_layout

@callback(
    Output({"component": "test", "index": 0}, "id"),
    Input("test3", "n_clicks"),
)
def update_id(clicks):
    # print(clicks)
    p = Patch()
    p["index"] = clicks
    return p


@callback(
    Output("id-test", "children"),
    Input({"component": "test", "index": 0}, "id"),
)
def _(id):
    return str(id)


if __name__ == "__main__":
    app.run_server(debug = True)

I guess that I would have envisioned changing the ID of the component would invalidate the callback that has the hardcoded 0 index, but it seems to continue working across multiple button clicks?

Edit: So I played around with it a bit more and I realized that I don’t have to even match the structure of the original id… I can replace it with anything that I want and the callbacks appear to be bound to the object, irrespective of the ID in question? Very confused right now

Hello @dash-beginner,

I believe that this would be because when the callback is originally registered, that it is identified as that component, and it is locked in.

An interesting thing would be what happens if you were to place it inside of a container and have a button that adds more of them. Then adjust the id’s inside the adding that would adjust any previous ids, my thinking is that it would break the originals. XD

Thanks for responding! Yeah, taking a deeper dive into it, I’m realizing that my initial plan of using callback context won’t work, because it seems as though that is bound to the original ID as well. I guess I’ll probably just update a store component instead and that should solve most things for me. Would love to figure out what the underlying mechanisms behind all of this stuff is someday.

1 Like