# Dash Callbacks: Chained Dropdowns, Pattern-Matching, Store and Clientside

> Dash callback patterns with complete apps: chained dropdowns, ctx.triggered_id, dcc.Store, pattern-matching callbacks with ALL and MATCH, Patch, clientside_callback, prevent_initial_call and allow_duplicate.

Source: https://www.pythoncharts.com/plotly/dash-callbacks/ | Published: 2026-12-06 | Author: Alex Scott | Category: Plotly | Tags: plotly, dash, callbacks, dashboard, web app

A Dash callback is a function decorated with `@callback(Output(...), Input(...))`. The tutorial on [your first Dash dashboard](https://www.pythoncharts.com/plotly/dash-tutorial-python-dashboard/) covers `Input`, `State` and multiple outputs. This post covers the patterns you reach for next: dropdowns that depend on each other, several buttons feeding one callback, sharing data between callbacks with `dcc.Store`, components created while the app runs (pattern-matching IDs and `Patch`), and callbacks that run in the browser. Everything targets Dash 4.5.

## Quick Example: Chained Dropdowns

A second dropdown whose options depend on the first needs two callbacks. One writes the options, and one draws the chart. This app uses simulated daily temperatures for twelve weather stations (a year of data each, seeded so you get the same numbers). Save it as `app.py`:

```python
import numpy as np
import pandas as pd
import plotly.express as px
from dash import Dash, Input, Output, callback, dcc, html

rng = np.random.default_rng(204)
# country: {station: (mean temperature, seasonal swing, +1 northern / -1 southern hemisphere)}
stations = {
    "Norway": {"Tromsø": (3, 9, 1), "Bergen": (8, 7, 1), "Oslo": (6, 11, 1)},
    "Spain": {"Madrid": (15, 10, 1), "Seville": (19, 9, 1), "Bilbao": (14, 6, 1)},
    "Kenya": {"Nairobi": (19, 1.5, 1), "Mombasa": (27, 2, 1), "Kisumu": (23, 1.5, 1)},
    "Chile": {"Santiago": (15, 8, -1), "Punta Arenas": (7, 5, -1), "Arica": (19, 4, -1)},
}
all_stations = [name for places in stations.values() for name in places]
days = pd.date_range("2025-01-01", periods=365)
season = -np.cos(2 * np.pi * (days.dayofyear - 15) / 365)   # coldest in mid-January

weather = pd.concat([
    pd.DataFrame({"date": days, "country": country, "station": station,
                  "temp_c": (mean + north * swing * season + rng.normal(0, 2, len(days))).round(1)})
    for country, places in stations.items()
    for station, (mean, swing, north) in places.items()
], ignore_index=True)

app = Dash()

app.layout = html.Div([
    html.H1("Station Temperatures"),
    dcc.Dropdown(list(stations), "Norway", id="country", clearable=False),
    dcc.Dropdown(id="station", clearable=False, style={"marginTop": "8px"}),
    dcc.Graph(id="temps"),
], style={"maxWidth": "800px", "margin": "auto", "fontFamily": "sans-serif"})

@callback(Output("station", "options"), Output("station", "value"), Input("country", "value"))
def station_options(country):
    names = list(stations[country])
    return names, names[0]          # options for the country, first one selected

@callback(Output("temps", "figure"), Input("station", "value"))
def draw(station):
    data = weather[weather["station"] == station].rename(columns={"temp_c": "Daily"})
    data["7-day average"] = data["Daily"].rolling(7, min_periods=1).mean()
    fig = px.line(data, x="date", y=["Daily", "7-day average"], template="plotly_white",
                  title=f"{station}: daily temperature",
                  labels={"date": "", "value": "°C", "variable": ""},
                  color_discrete_sequence=["#b6c2cf", "#0f766e"])
    return fig

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

![Dash app with a country dropdown set to Norway, a station dropdown set to Tromsø and a line chart of daily temperature with a seven day average](https://www.pythoncharts.com/plotly/dash-callbacks/images/dash-chained-dropdowns.png)

When the country changes, `station_options` returns a new option list and a new value. Changing the `station` value then triggers `draw`. Dash orders the callbacks from the `Output` and `Input` links, so on page load it fills the station dropdown first and only then draws the chart, and `draw` never receives `None`.

Each later example reuses the imports and data from this one, so **replace everything from `app = Dash()` down** and add any new imports shown.

## Which Button Was Clicked? `ctx.triggered_id`

When several inputs feed one callback, `ctx.triggered_id` holds the `id` of the one that fired. It is `None` on page load, which makes a handy default:

```python
from dash import ctx

app = Dash()

app.layout = html.Div([
    html.H2("Country averages"),
    html.Div([
        html.Button("Last 30 days", id="btn-30"),
        html.Button("Last 90 days", id="btn-90"),
        html.Button("Full year", id="btn-365"),
    ], style={"display": "flex", "gap": "8px", "marginBottom": "10px"}),
    dcc.Graph(id="countries"),
], style={"maxWidth": "800px", "margin": "auto", "fontFamily": "sans-serif"})

@callback(
    Output("countries", "figure"),
    Input("btn-30", "n_clicks"),
    Input("btn-90", "n_clicks"),
    Input("btn-365", "n_clicks"),
)
def show_window(*_clicks):
    window = {"btn-30": 30, "btn-90": 90}.get(ctx.triggered_id, 365)
    recent = weather[weather["date"] > days[-1] - pd.Timedelta(days=window)]
    daily = recent.groupby(["date", "country"], as_index=False)["temp_c"].mean()
    return px.line(daily, x="date", y="temp_c", color="country", template="plotly_white",
                   title=f"Mean temperature, last {window} days",
                   labels={"date": "", "temp_c": "°C", "country": ""})

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

![Dash app with three window buttons and a line chart of mean temperature for four countries over the last 30 days](https://www.pythoncharts.com/plotly/dash-callbacks/images/dash-triggered-id.png)

The same app with `ctx.triggered_id` and `Input("btn-30", "n_clicks")` is how you build "reset" and "apply" buttons next to ordinary controls. `ctx.triggered_id` replaces the older `dash.callback_context.triggered[0]["prop_id"].split(".")[0]`.

## Share Data Between Callbacks with `dcc.Store`

Callbacks can't share Python variables that change per user, because module-level objects are shared by everyone. Put per-user data in a `dcc.Store`, which lives in the browser. One callback does the filtering and grouping, and any number of callbacks read the result:

```python
app = Dash()

app.layout = html.Div([
    html.H2("One filter, two charts"),
    dcc.Dropdown(list(stations), "Spain", id="country", clearable=False),
    dcc.Store(id="daily"),
    dcc.Graph(id="range-chart"),
    dcc.Graph(id="monthly-chart"),
], style={"maxWidth": "800px", "margin": "auto", "fontFamily": "sans-serif"})

@callback(Output("daily", "data"), Input("country", "value"))
def summarize(country):
    data = weather[weather["country"] == country]
    daily = data.groupby("date")["temp_c"].agg(["min", "mean", "max"]).reset_index()
    return daily.to_dict("records")          # must be JSON-serializable

@callback(Output("range-chart", "figure"), Input("daily", "data"))
def draw_range(records):
    daily = pd.DataFrame(records)
    fig = px.line(daily, x="date", y=["max", "mean", "min"], template="plotly_white",
                  render_mode="svg", title="Hottest, average and coldest station each day",
                  labels={"date": "", "value": "°C", "variable": ""},
                  color_discrete_sequence=["#e76f51", "#264653", "#2a9d8f"])
    return fig

@callback(Output("monthly-chart", "figure"), Input("daily", "data"))
def draw_monthly(records):
    daily = pd.DataFrame(records)
    daily["month"] = pd.to_datetime(daily["date"]).dt.strftime("%b")
    monthly = daily.groupby("month", sort=False)["mean"].mean().reset_index()
    return px.bar(monthly, x="month", y="mean", template="plotly_white",
                  title="Average temperature by month", labels={"month": "", "mean": "°C"},
                  color_discrete_sequence=["#264653"])

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

![Dash app with a country dropdown set to Spain, a line chart of daily maximum, mean and minimum temperature and a bar chart of monthly average temperature](https://www.pythoncharts.com/plotly/dash-callbacks/images/dash-store.png)

The `render_mode="svg"` argument is there because `px.line` switches to WebGL when the data frame has more than 1,000 rows (this one has 1,095 after Plotly stacks the three columns), which is fast for big data but not needed here.

Everything in a `Store` is sent to the browser and back on every callback that uses it, so keep it small (summaries, not raw rows). With `storage_type="session"` or `"local"` the data survives a page reload. For big data frames, compute them once at startup, or cache the function with `functools.lru_cache` or Flask-Caching, and pass only a key through the callback.

## Create Components on the Fly: Pattern-Matching Callbacks and `Patch`

When the number of components isn't known in advance, give each one a dictionary `id` instead of a string. Then `ALL` collects every match into a list, and `MATCH` handles each component separately. `Patch` appends to an existing property without resending all of it:

```python
from dash import ALL, MATCH, Patch

def row(index, value=None):
    return html.Div([
        dcc.Dropdown(all_stations, value, id={"type": "pick", "index": index},
                     placeholder="Pick a station", style={"flex": "1"}),
        html.Span(id={"type": "mean", "index": index}, style={"width": "110px"}),
    ], style={"display": "flex", "gap": "10px", "alignItems": "center", "marginBottom": "6px"})

app = Dash()

app.layout = html.Div([
    html.H2("Compare stations"),
    html.Div([row(0, "Oslo"), row(1, "Madrid")], id="rows"),
    html.Button("Add station", id="add"),
    dcc.Graph(id="compare"),
], style={"maxWidth": "800px", "margin": "auto", "fontFamily": "sans-serif"})

@callback(Output("rows", "children"), Input("add", "n_clicks"), prevent_initial_call=True)
def add_row(n_clicks):
    patch = Patch()
    patch.append(row(n_clicks))          # id index = number of clicks, so each is unique
    return patch

@callback(Output({"type": "mean", "index": MATCH}, "children"),
          Input({"type": "pick", "index": MATCH}, "value"))
def show_mean(station):
    if not station:
        return ""
    return f"mean {weather.loc[weather['station'] == station, 'temp_c'].mean():.1f} °C"

@callback(Output("compare", "figure"), Input({"type": "pick", "index": ALL}, "value"))
def compare(picked):
    chosen = [station for station in picked if station]
    data = weather[weather["station"].isin(chosen)]
    monthly = data.groupby([data["date"].dt.month, "station"], as_index=False)["temp_c"].mean()
    return px.line(monthly, x="date", y="temp_c", color="station", markers=True,
                   template="plotly_white", title="Monthly mean temperature",
                   labels={"date": "Month", "temp_c": "°C", "station": ""})

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

![Dash app with dropdowns for Oslo and Madrid showing their mean temperatures, a third empty dropdown added by the Add station button and a line chart of monthly mean temperature for both stations](https://www.pythoncharts.com/plotly/dash-callbacks/images/dash-pattern-matching.png)

The pieces:

- `{"type": "pick", "index": 0}` is an ordinary `id`, just a dictionary. Dash matches on the keys, so `type` groups components and `index` tells them apart.
- `Input({"type": "pick", "index": ALL}, "value")` receives a list of every matching dropdown's value, including `None` for the empty ones. Filter those out, as `compare` does.
- `MATCH` in both the `Input` and the `Output` runs the callback once per component and sends each result to the component with the same `index`.
- Callbacks with `ALL` or `MATCH` don't need `suppress_callback_exceptions=True` even when the components are created later.
- `Patch()` records changes (`append`, `extend`, `insert`, item assignment) and sends only those. Use it for a growing list, or to change one trace of a large figure without rebuilding it.

## Run a Callback in the Browser: `clientside_callback`

A callback that only reshapes data you already have doesn't need a trip to the server. `clientside_callback` takes JavaScript instead of a Python function, with the same `Output` and `Input` arguments. Here the server picks the station, and switching between Celsius and Fahrenheit happens in the browser:

```python
from dash import clientside_callback

app = Dash()

app.layout = html.Div([
    html.H2("Switch units without a round trip"),
    html.Div([
        dcc.Dropdown(all_stations, "Bergen", id="station", clearable=False, style={"flex": "1"}),
        dcc.RadioItems(["°C", "°F"], "°C", id="unit", inline=True),
    ], style={"display": "flex", "gap": "20px", "alignItems": "center"}),
    dcc.Store(id="series"),
    dcc.Graph(id="temps"),
], style={"maxWidth": "800px", "margin": "auto", "fontFamily": "sans-serif"})

@callback(Output("series", "data"), Input("station", "value"))
def load_series(station):
    data = weather[weather["station"] == station]
    return {"station": station, "date": data["date"].dt.strftime("%Y-%m-%d").tolist(),
            "temp_c": data["temp_c"].tolist()}

clientside_callback(
    """
    function(series, unit) {
        const convert = unit === "°F" ? c => c * 9 / 5 + 32 : c => c;
        return {
            data: [{x: series.date, y: series.temp_c.map(convert), type: "scatter",
                    mode: "lines", line: {color: "#0f766e", width: 1.5}}],
            layout: {title: {text: series.station + ": daily temperature"},
                     yaxis: {title: {text: unit}, gridcolor: "#e2e8f0"},
                     plot_bgcolor: "white", margin: {t: 60, r: 20}}
        };
    }
    """,
    Output("temps", "figure"),
    Input("series", "data"),
    Input("unit", "value"),
)

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

![Dash app showing the daily temperature of the Bergen station in degrees Fahrenheit after switching the radio button from Celsius](https://www.pythoncharts.com/plotly/dash-callbacks/images/dash-clientside.png)

The JavaScript receives the `Input` values in order and returns the new `Output` value. Because the figure is plain JSON, the function builds it directly. Don't pass a Plotly figure object from Python into clientside code and loop over its arrays: Plotly 6 encodes NumPy arrays in binary form when it serializes a figure, so `trace.y` is not a plain list. For anything heavier than a conversion, keep the callback in Python.

## Stop Callbacks Firing: `prevent_initial_call`, `PreventUpdate` and `no_update`

Dash runs every callback once when the page loads. These three tools control when a callback actually changes something:

```python
from dash import no_update
from dash.exceptions import PreventUpdate

@callback(Output("rows", "children"), Input("add", "n_clicks"),
          prevent_initial_call=True)             # don't run on page load
def add_row(n_clicks):
    ...

@callback(Output("temps", "figure"), Output("note", "children"), Input("station", "value"))
def draw(station):
    if station is None:
        raise PreventUpdate                      # change nothing, keep every output as it is
    if station not in all_stations:
        return no_update, "Unknown station"      # keep the figure, update the note
    ...
```

`prevent_initial_call=True` skips only the page-load run. `PreventUpdate` leaves all outputs alone for that run, and `no_update` leaves one output alone.

Two callbacks can't write to the same `Output` unless the extra one sets `allow_duplicate=True` and `prevent_initial_call=True`, for example `Output("temps", "figure", allow_duplicate=True)`. Use it for a "reset" button that lives apart from the main callback.

## Which Callback Feature Should I Use?

| You want | Use |
|---|---|
| Update one output when a control changes | `Input` and `Output` |
| Read a value without triggering | `State` |
| Know which of several inputs fired | `ctx.triggered_id` |
| Options for one control that depend on another | A callback with the options as `Output` |
| Share computed data across callbacks | `dcc.Store` |
| A variable number of components | Dictionary IDs with `ALL` and `MATCH` |
| Add to a list or one part of a figure | `Patch()` |
| Instant response with no server work | `clientside_callback` |
| A long-running computation | `@callback(..., background=True)` with a background callback manager |

## Practical Tips

- **Keep callbacks short.** A callback that loads, filters, groups and draws is hard to debug. Split it so one callback holds the expensive step.
- **Return the same shape every time.** A callback with two `Output`s must always return two values, even when it returns early.
- **Watch the order of arguments.** They follow the order of the `Input` and `State` lines, not their names.
- **Never modify globals inside a callback.** Every user shares them, and Dash may run several worker processes. Use `dcc.Store` or a database.
- **Use `debug=True` while building.** The callback graph button in the debug panel shows which callbacks feed which components.

## Similar Topics

- [Dash Tutorial: Build Your First Dashboard in Python](https://www.pythoncharts.com/plotly/dash-tutorial-python-dashboard/)
- [Streamlit vs Dash vs Shiny vs Gradio vs Panel](https://www.pythoncharts.com/python/streamlit-vs-dash-vs-shiny-vs-gradio-vs-panel/)
- [Plotly Range Slider and Selector for Time Series](https://www.pythoncharts.com/plotly/range-slider-selector-time-series/)
