Clientside Callbacks

To get the most out of this page, make sure you’ve read about Basic Callbacks in the Dash Fundamentals.

Sometimes callbacks can incur a significant overhead, especially when they:
- receive and/or return very large quantities of data (transfer time)
- are called very often (network latency, queuing, handshake)
- are part of a callback chain that requires multiple roundtrips between the browser and Dash

When the overhead cost of a callback becomes too great and no other optimization is possible, the callback can be modified to be run
directly in the browser instead of a making a request to Dash.

The syntax for the callback is almost exactly the same; you use
Input and Output as you normally would when declaring a callback,
but you also define a JavaScript function as the first argument to the
@callback decorator.

For example, the following callback:


@callback(
    Output('out-component', 'value'),
    Input('in-component1', 'value'),
    Input('in-component2', 'value')
)
def large_params_function(largeValue1, largeValue2):
    largeValueOutput = someTransform(largeValue1, largeValue2)

    return largeValueOutput

Can be rewritten to use JavaScript like so:

from dash import clientside_callback, Input, Output

clientside_callback(
    """
    function(largeValue1, largeValue2) {
        return someTransform(largeValue1, largeValue2);
    }
    """,
    Output('out-component', 'value'),
    Input('in-component1', 'value'),
    Input('in-component2', 'value')
)


You also have the option of defining the function in a .js file in
your assets/ folder. To achieve the same result as the code above,
the contents of the .js file would look like this:

window.dash_clientside = Object.assign({}, window.dash_clientside, {
    clientside: {
        large_params_function: function(largeValue1, largeValue2) {
            return someTransform(largeValue1, largeValue2);
        }
    }
});

In Dash, the callback would now be written as:

from dash import clientside_callback, ClientsideFunction, Input, Output

clientside_callback(
    ClientsideFunction(
        namespace='clientside',
        function_name='large_params_function'
    ),
    Output('out-component', 'value'),
    Input('in-component1', 'value'),
    Input('in-component2', 'value')
)

A Simple Example

Below are two examples of using clientside callbacks to update a
graph in conjunction with a dcc.Store component. In these
examples, we update a dcc.Store
component on the backend; to create and display the graph, we have a clientside callback in the
frontend that adds some extra information about the layout that we
specify using the radio buttons under “Graph scale”.

from dash import Dash, dcc, html, Input, Output, callback, clientside_callback
import pandas as pd

import json

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = Dash(__name__, external_stylesheets=external_stylesheets)

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')

available_countries = df['country'].unique()

app.layout = html.Div([
    dcc.Graph(
        id='clientside-graph'
    ),
    dcc.Store(
        id='clientside-figure-store',
        data=[{
            'x': df[df['country'] == 'Canada']['year'],
            'y': df[df['country'] == 'Canada']['pop']
        }]
    ),
    'Indicator',
    dcc.Dropdown(
        {'pop' : 'Population', 'lifeExp': 'Life Expectancy', 'gdpPercap': 'GDP per Capita'},
        'pop',
        id='clientside-graph-indicator'
    ),
    'Country',
    dcc.Dropdown(available_countries, 'Canada', id='clientside-graph-country'),
    'Graph scale',
    dcc.RadioItems(
        ['linear', 'log'],
        'linear',
        id='clientside-graph-scale'
    ),
    html.Hr(),
    html.Details([
        html.Summary('Contents of figure storage'),
        dcc.Markdown(
            id='clientside-figure-json'
        )
    ])
])


@callback(
    Output('clientside-figure-store', 'data'),
    Input('clientside-graph-indicator', 'value'),
    Input('clientside-graph-country', 'value')
)
def update_store_data(indicator, country):
    dff = df[df['country'] == country]
    return [{
        'x': dff['year'],
        'y': dff[indicator],
        'mode': 'markers'
    }]


clientside_callback(
    """
    function(data, scale) {
        return {
            'data': data,
            'layout': {
                 'yaxis': {'type': scale}
             }
        }
    }
    """,
    Output('clientside-graph', 'figure'),
    Input('clientside-figure-store', 'data'),
    Input('clientside-graph-scale', 'value')
)


@callback(
    Output('clientside-figure-json', 'children'),
    Input('clientside-figure-store', 'data')
)
def generated_figure_json(data):
    return '```\n'+json.dumps(data, indent=2)+'\n```'


if __name__ == '__main__':
    app.run(debug=True)
Indicator
Country
Graph scale

Contents of figure storage

None

Note that, in this example, we are manually creating the figure
dictionary by extracting the relevant data from the
dataframe. This is what gets stored in our
dcc.Store component;
expand the “Contents of figure storage” above to see exactly what
is used to construct the graph.

Using Plotly Express to Generate a Figure

Plotly Express enables you to create one-line declarations of
figures. When you create a graph with, for example,
plotly_express.Scatter, you get a dictionary as a return
value. This dictionary is in the same shape as the figure
argument to a dcc.Graph component. (See
here for
more information about the shape of figures.)

We can rework the example above to use Plotly Express.

from dash import Dash, dcc, html, Input, Output, callback, clientside_callback
import pandas as pd
import json

import plotly.express as px

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = Dash(__name__, external_stylesheets=external_stylesheets)

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')

available_countries = df['country'].unique()

app.layout = html.Div([
    dcc.Graph(
        id='clientside-graph-px'
    ),
    dcc.Store(
        id='clientside-figure-store-px'
    ),
    'Indicator',
    dcc.Dropdown(
        {'pop' : 'Population', 'lifeExp': 'Life Expectancy', 'gdpPercap': 'GDP per Capita'},
        'pop',
        id='clientside-graph-indicator-px'
    ),
    'Country',
    dcc.Dropdown(available_countries, 'Canada', id='clientside-graph-country-px'),
    'Graph scale',
    dcc.RadioItems(
        ['linear', 'log'],
        'linear',
        id='clientside-graph-scale-px'
    ),
    html.Hr(),
    html.Details([
        html.Summary('Contents of figure storage'),
        dcc.Markdown(
            id='clientside-figure-json-px'
        )
    ])
])


@callback(
    Output('clientside-figure-store-px', 'data'),
    Input('clientside-graph-indicator-px', 'value'),
    Input('clientside-graph-country-px', 'value')
)
def update_store_data(indicator, country):
    dff = df[df['country'] == country]
    return px.scatter(dff, x='year', y=str(indicator))


clientside_callback(
    """
    function(figure, scale) {
        if(figure === undefined) {
            return {'data': [], 'layout': {}};
        }
        const fig = Object.assign({}, figure, {
            'layout': {
                ...figure.layout,
                'yaxis': {
                    ...figure.layout.yaxis, type: scale
                }
             }
        });
        return fig;
    }
    """,
    Output('clientside-graph-px', 'figure'),
    Input('clientside-figure-store-px', 'data'),
    Input('clientside-graph-scale-px', 'value')
)


@callback(
    Output('clientside-figure-json-px', 'children'),
    Input('clientside-figure-store-px', 'data')
)
def generated_px_figure_json(data):
    return '```\n'+json.dumps(data, indent=2)+'\n```'


if __name__ == '__main__':
    app.run(debug=True)
Indicator
Country
Graph scale

Contents of figure storage

None

Again, you can expand the “Contents of figure storage” section
above to see what gets generated. You may notice that this is
quite a bit more extensive than the previous example; in
particular, a layout is already defined. So, instead of creating
a layout as we did previously, we have to mutate the existing
layout in our JavaScript code.

Clientside Callbacks with Promises

Dash 2.4 and later supports clientside callbacks that return promises.

Fetching Data Example

In this example, we fetch data (based on the value of the dropdown) using an async clientside callback function that outputs it to a dash_table.DataTable component.

from dash import Dash, dcc, html, Input, Output, dash_table, clientside_callback

app = Dash(__name__)

app.layout = html.Div(
    [
        dcc.Dropdown(
            options=[
                {
                    "label": "Car-sharing data",
                    "value": "https://raw.githubusercontent.com/plotly/datasets/master/carshare_data.json",
                },
                {
                    "label": "Iris data",
                    "value": "https://raw.githubusercontent.com/plotly/datasets/master/iris_data.json",
                },
            ],
            value="https://raw.githubusercontent.com/plotly/datasets/master/iris_data.json",
            id="data-select",
        ),
        html.Br(),
        dash_table.DataTable(id="my-table-promises", page_size=10),
    ]
)

clientside_callback(
    """
    async function(value) {
    const response = await fetch(value);
    const data = await response.json();
    return data;
    }
    """,
    Output("my-table-promises", "data"),
    Input("data-select", "value"),
)

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

Notifications Example

This example uses promises and sends desktop notifications to the user once they grant permission and select the Notify button:

from dash import Dash, dcc, html, Input, Output, clientside_callback

app = Dash(__name__)

app.layout = html.Div(
    [
        dcc.Store(id="notification-permission"),
        html.Button("Notify", id="notify-btn"),
        html.Div(id="notification-output"),
    ]
)


clientside_callback(
    """
    function() {
        return navigator.permissions.query({name:'notifications'})
    }
    """,
    Output("notification-permission", "data"),
    Input("notify-btn", "n_clicks"),
    prevent_initial_call=True,
)

clientside_callback(
    """
    function(result) {
        if (result.state == 'granted') {
            new Notification("Dash notification", { body: "Notification already granted!"});
            return null;
        } else if (result.state == 'prompt') {
            return new Promise((resolve, reject) => {
                Notification.requestPermission().then(res => {
                    if (res == 'granted') {
                        new Notification("Dash notification", { body: "Notification granted!"});
                        resolve();
                    } else {
                        reject(`Permission not granted: ${res}`)
                    }
                })
            });
        } else {
            return result.state;
        }
    }
    """,
    Output("notification-output", "children"),
    Input("notification-permission", "data"),
    prevent_initial_call=True,
)

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

Notification with promises


Callback Context

You can use dash_clientside.callback_context.triggered_id within a clientside callback to access the ID of the component that triggered the callback.

In this example, we display the triggered_id in the app when a button is clicked.

from dash import Dash, html, Input, Output

app = Dash(prevent_initial_callbacks=True)

app.layout = html.Div(
    [
        html.Button("Button 1", id="btn1"),
        html.Button("Button 2", id="btn2"),
        html.Button("Button 3", id="btn3"),
        html.Div(id="log"),
    ]
)

app.clientside_callback(
    """
    function(){
        console.log(dash_clientside.callback_context);
        const triggered_id = dash_clientside.callback_context.triggered_id;
        return "triggered id: " + triggered_id
    }
    """,
    Output("log", "children"),
    Input("btn1", "n_clicks"),
    Input("btn2", "n_clicks"),
    Input("btn3", "n_clicks"),
)

if __name__ == "__main__":
    app.run()

Set Props

New in 2.16

dash_clientside.set_props allows you to update a Dash component property directly instead of updating it by having it as an output of a clientside callback. This can be useful if you have a non-Dash component (for example, a custom JavaScript component) that you want to update a Dash component property from, or if you want to implement custom functionality that is not available directly within Dash but that interacts with Dash.

For an example of using set_props with a custom JavaScript component, go to the community-driven Dash Example Index.

The following example adds an event listener to the page. This event listener responds to the user pressing <kbd>Ctrl<kbd>+<kbd>R<kbd> by updating a dcc.Store component’s data. Another callback has the dcc.Store component’s data property as an input so runs each time it changes, outputting the updated data to an html.Div component.

from dash import Dash, html, dcc, Input, Output

app = Dash()

app.layout = html.Div(
    [
        html.Span(
            [
                "Press ",
                html.Kbd("Ctrl"),
                " + ",
                html.Kbd("R"),
                " to refresh the app's data",
            ]
        ),
        dcc.Store(id="store-events", data={}),
        html.Div(id="container-events"),
    ],
    id="document",
)


app.clientside_callback(
    """
    function () {
        document.addEventListener('keydown', function(e) {

            if (e.ctrlKey && e.keyCode == 82) {
                // Simulate getting new data
                newData = JSON.stringify(new Date())

                // Update dcc.Store with ID store-events
                dash_clientside.set_props("store-events", {data: newData})

                event.preventDefault()
                event.stopPropagation()
                return dash_clientside.no_update;
            }
        });
        return dash_clientside.no_update;
    }
    """,
    Output('document', 'id'),
    Input('document', 'id'),
)


@app.callback(
    Output('container-events', 'children'),
    Input('store-events', 'data'),
    prevent_initial_call=True
)
def handle_key_press(data):
    return f"Current data value: {data}"


if __name__ == '__main__':
    app.run(debug=True)
Press Ctrl + R to refresh the app's data

Notes about this example

Limitations

There are a few limitations to keep in mind:

  1. Clientside callbacks execute on the browser’s main thread and will block
    rendering and events processing while being executed.
  2. Clientside callbacks are not possible if you need to refer to global
    variables on the server or a DB call is required.
  3. Dash versions prior to 2.4.0 do not support asynchronous clientside callbacks and will
    fail if a Promise is returned.