Python Tutorial
Dash Callbacks
A callback runs Python when an input changes and writes the result to an output component.
Input and Output
from dash import Dash, html, dcc, Input, Output, callback
app = Dash(__name__)
app.layout = html.Div([
dcc.Input(id="name", value="Ada", type="text"),
html.H2(id="out"),
])
@callback(Output("out", "children"), Input("name", "value"))
def greet(name):
return f"Hello, {name or 'friend'}!"
if __name__ == "__main__":
app.run(debug=True)State
State reads a value without triggering the callback. Use it for a form that only runs when a button is clicked:
from dash import State
@callback(
Output("out", "children"),
Input("go", "n_clicks"),
State("name", "value"),
prevent_initial_call=True,
)
def on_click(n, name):
return f"Submitted: {name}"📘 Real-World Deep Dive
Knowing <strong>Dash Callbacks (Dash)</strong> well is what turns Dash from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Dash Callbacks that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from dash import Input, Output, callback
from dash import dcc, html
@callback(Output("out","children"), Input("in","value"))
def update(v):
return f"You typed {v!r}"Expected Output
(no output)Common mistakes
- Callbacks must declare
Output/Input/Statein the right order; mismatched component IDs silently produce empty updates. @app.callbackbody cannot read HTML — return only data, render in the layout.- Each request lifecycle can fire callbacks many times — debounce heavy computation with
dcc.Intervalor caching. - Treating Dash Callbacks as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Use
functools.lru_cacheon expensive data-loaders prefixed by their inputs. - Switch large tables to
dash_table.DataTablewithvirtualization=True. - Run in production with
gunicorn --workers 4 --threads 8and proxy through nginx. - When working with Dash, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.