Dash Callback Function
Dash allows developers to use Python to create dynamic, responsive user interfaces.
One of Dash's core features is the callback function (Callback), which enables the user interface to update in real time based on user input or actions.
The callback function is the core mechanism in Dash for handling user interaction. It allows you to dynamically update the application's layout or data when the user interacts with the application. Simply put, a callback is a Python function that is triggered when specific inputs change, and updates the output based on those input changes.
A typical Dash callback function consists of the following parts:
- Input: specifies which component's property changes will trigger the callback function.
- Output: specifies which component's properties will be updated after the callback function executes.
- State: optional parameter used to pass data that will not trigger the callback but is needed within it.
- Callback Function Body: contains the actual logic code used to process inputs and generate outputs.
Basic Structure of a Callback Function
@app.callback(
Output(component_id='output-component', component_property='output-property'),
Input(component_id='input-component', component_property='input-property')
)
def update_output(input_value):
# Calculate output value based on input value
return output_value
-
Output:
Specify the output target of the callback function.
component_id: the ID of the target component.
component_property: the property of the target component (such as children, value etc.).
Specify the output target of the callback function.
-component_id: the ID of the target component.
component_property: the property of the target component (such as children, value etc.).
-
Input:
Specify the input source of the callback function.
component_id: the ID of the input component.
component_property: the property of the input component (such as value, n_clicks etc.).
Specify the input source of the callback function.
-component_id: the ID of the input component.
component_property: the property of the input component (such as value, n_clicks etc.).
-
Callback Function:
Receives input values, computes, and returns output values.
The function name can be customized (e.g. update_output).
Receives input values, computes, and returns output values.
-The function name can be customized (e.g. update_output).
Example
The following example shows how to dynamically update text content based on the input box's value:
Example
from
dash
import
Dash
,
html
,
dcc
,
Input
,
Output
Create the Dash App
app
=
Dash
(
name
)
Define the Layout
app.
layout
=
html.
Div
(
[
dcc.
Input
(
id
=
'input'
,
type
=
'text'
,
placeholder
=
'Please enter something...'
)
,
html.
Div
(
id
=
'output'
)
]
)
Define the Callback Function
@
app.
callback
(
Output
(
'output'
,
'children'
)
,
Input
(
'input'
,
'value'
)
)
def
update_output
(
input_value
)
:
return
f
'You entered: {input_value}'
Run the application
if
name
==
'main'
:
app.
run
(
debug
=
True
)
The following example shows how to dynamically update a chart based on the dropdown menu selection:
Example
from
dash
import
Dash
,
html
,
dcc
,
Input
,
Output
import
plotly.
express
as
px
import
pandas
as
pd
Create the Dash App
app
=
Dash
(
name
)
Sample data
df
=
pd.
DataFrame
(
{
'City'
:
[
'Beijing'
,
'Shanghai'
,
'Guangzhou'
,
'Shenzhen'
]
,
'Population'
:
[
2171
,
2424
,
1490
,
1303
]
}
)
Define the Layout
app.
layout
=
html.
Div
(
[
dcc.
Dropdown
(
id
=
'dropdown'
,
options
=
[
{
'label'
: city
,
'value'
: city
}
for
city
in
df
[
'City'
]
]
,
value
=
'Beijing'
Default value
)
,
dcc.
Graph
(
id
=
'graph'
)
]
)
Define the Callback Function
@
app.
callback
(
Output
(
'graph'
,
'figure'
)
,
Input
(
'dropdown'
,
'value'
)
)
def
update_graph
(
selected_city
)
:
filtered_df
=
df
[
df
[
'City'
]
==
selected_city
]
fig
=
px.
bar
(
filtered_df
,
x
=
'City'
,
y
=
'Population'
,
title
=
f
'{selected_city} Population Data'
)
return
fig
Run the application
if
name
==
'main'
:
app.
run
(
debug
=
True
)
After the above code runs, selecting a city in the dropdown menu will dynamically update the chart to display that city's population data.

In the following example, after the user enters a number, the square of that number is displayed:
Example
from
dash
import
Dash
,
html
,
dcc
,
Input
,
Output
Create the Dash App
app
=
Dash
(
name
)
Define the Layout
app.
layout
=
html.
Div
(
[
html.
H1
(
"Calculate Square"
)
,
Title
dcc.
Input
(
id
=
'number-input'
,
The input box's ID
type
=
'number'
,
The input box type is number
placeholder
=
'Please enter a number...'
,
The input box's placeholder text
value
=
''
The initial value is empty
)
,
html.
Div
(
id
=
'output'
)
The Div used to display the result
]
)
Define the Callback Function
@
app.
callback
(
Output
(
'output'
,
'children'
)
,
Output to the children property of the Div with id 'output'
Input
(
'number-input'
,
'value'
)
The input comes from the value property of the input box with id 'number-input'
)
def
calculate_square
(
number
)
:
if
number
is
None
or
number
==
''
:
If the input is empty
return
'Please enter a number.'
try
:
number
=
float
(
number
)
Convert the input to a float
square
=
number **
2
Calculate the square
return
f
'The square of {number} is: {square}'
Return result
except
ValueError
:
If the input is not a number
return
'Please enter a valid number.'
Run the application
if
name
==
'main'
:
app.
run
(
debug
=
True
)
Start the app; debug=True enables debug mode
Code explanation:
1. Layout Section:
-
Use
html.H1Create a title "Calculate Square". -
Use
dcc.InputCreate a number input box,idisnumber-input, with typenumber. -
Use
html.DivCreate an area for displaying the result,idisoutput.
2. Callback Function:
-
Use
@app.callbackThe decorator defines the callback function. -
The input is
number-inputthe input box'svalueattribute. -
The output is
outputthe Div'schildrenattribute. -
In the callback function:
-
Check whether the input is empty.
-
Convert the input to a float and calculate its square.
-
Return the formatted result.
Check whether the input is empty.
-Convert the input to a float and calculate its square.
-Return the formatted result.
3. Run the App: When using app.run(debug=True) Start the app,debug=True indicates debug mode is enabled; the running effect is shown below:

How a Callback Function Works
1. Binding of Input and Output
In Dash, the input and output of a callback function are specified through the Input and Output object.Input The object specifies which properties of which components changing will trigger the callback function, while the Output object specifies which properties of which components will be updated after the callback function executes.
2. Triggering of the Callback Function
When the user performs operations on the interface (such as entering text or clicking a button), the relevant component properties change. Dash detects these changes and automatically invokes the bound callback function.
3. Execution of the Callback Function
When the callback function executes, Dash passes the current value of the input property as a parameter to the callback function. The callback function computes or processes based on these input values and returns the new value of the output property. Dash automatically updates the returned value to the specified component property.
Advanced Usage of Callback Functions
1. Multiple Inputs and Outputs
A callback function can have multiple inputs and outputs. For example:
Example
@
app.
callback
(
[
Output
(
'output-div-1'
,
'children'
)
,
Output
(
'output-div-2'
,
'children'
)
]
,
[
Input
(
'input-1'
,
'value'
)
,
Input
(
'input-2'
,
'value'
)
]
)
def
update_outputs
(
input1
,
input2
)
:
return
f
'Input 1: {input1}'
,
f
'Input 2: {input2}'
In this example, the callback functionupdate_outputshas two inputs and two outputs. Wheninput-1orinput-2changes, the callback function is triggered and updates the two output components'childrenattribute.
2. Using State
Sometimes you may need to use data within a callback function that does not trigger the callback. In such cases, you can use theStateobject.Stateobject, which is similar to theInputobject, but it does not trigger the callback function.
Example
@
app.
callback
(
Output
(
'output-div'
,
'children'
)
,
[
Input
(
'submit-button'
,
'n_clicks'
)
]
,
[
State
(
'input-text'
,
'value'
)
]
)
def
update_output
(
n_clicks
,
input_value
)
:
if
n_clicks
is
None
:
return
'No clicks yet'
return
f
'Button clicked {n_clicks} times. Input: {input_value}'
In this example,n_clicksis the input that triggers the callback, whileinput_valueis the state used in the callback function. The callback function is triggered only when the button is clicked, but it can use the current value of the input box.
3. Preventing Redundant Callback Execution
In some cases, a callback function may be triggered frequently, causing performance issues. To avoid this, you can usedash.no_updateto prevent unnecessary updates.
Example
@
app.
callback
(
Output
(
'output-div'
,
'children'
)
,
[
Input
(
'input-text'
,
'value'
)
]
)
def
update_output
(
input_value
)
:
if
not
input_value:
return
dash.
no_update
return
f
'You have entered: {input_value}'
In this example, if the input box value is empty, the callback function will not update the output component.
Common Problems and Solutions
1. Callback Function Not Triggered
If the callback function is not triggered as expected, it may be due to one of the following reasons:
- Input or output ID mismatch: Ensure that
InputandOutput: ensure the component ID in it matches the ID in the layout. - Incorrect property name: Ensure that
InputandOutput: ensure the property name in it is correct. - Callback function not registered: ensure the callback function is correctly registered with the application.
2. Callback Function Executes Slowly
If the callback function executes slowly, consider the following optimization methods:
- Reduce the computation in the callback function: avoid complex computations inside the callback function as much as possible.
- Use caching: for repeated computation results, use caching to reduce computation time.
- Asynchronous callbacks: for long-running tasks, use asynchronous callbacks to avoid blocking the main thread.